search
HomeWeb Front-endJS TutorialjQuery implements the method of sliding left to appear delete button

This article mainly introduces the example of the delete button appearing on the left slide based on jQuery. The detailed code is compiled here, which is of great practical value. Friends who need it can refer to it. I hope it can help everyone.

Recently when I was working on a project, I encountered a need to implement a delete button effect similar to the QQ conversation list on the left swipe, so I tried to write one and share it with everyone. , God, don’t spray.

Basic requirements

Since we are making a cross-platform APP, part of the interface is actually a webpage loaded by WebView, so we need to use a webpage to achieve this effect: When you slide to the left, the delete button is displayed, and when you slide to the right, the delete button is hidden.

Sample picture of the finished product

Well, let’s take the picture first. The following are the effects in PC browser and Mobile browser respectively.

PC browser


Mobile browser

Implementation ideas

In order to illustrate my implementation ideas, I made two pictures to assist the explanation.

First, please look at Figure 1. In the picture, we set the width of each row to exceed the width of the browser, and the excess part is the area where the button is placed. Since the maximum width of the browser is exceeded, the button area is not visible at this time and only the general information section on the left is displayed.

Figure 1 Normal state

Next, we monitor the general information area on the left and monitor the sliding event (the specific method of monitoring is not considered yet). When we listen to the left swipe event, we offset the corresponding row to the left so that the button is displayed, and the excess left part is blocked (see Figure 2).

Figure 2 Left sliding state

When we slide right, we can return the corresponding row to the time when the left offset is 0 .

Key implementation method

For left sliding and right sliding, we implement it by setting the margin-left of the general information area. When the margin-left is set to negative When the margin-left is set to 0 again, the left slide is realized.

For sliding event monitoring, it is implemented by monitoring the mouse (finger) press and lift, and determine whether to slide right or left based on the positive or negative difference between the X coordinates of the two points.

Complete code

It should be noted that when I tested, I used chrome’s normal mode and mobile simulator mode, and found two modes The next monitor is different, so I wrote two monitors so that at least one of them will be executed. There may be other better adaptation methods, but they are not the focus here. Of course, everyone is welcome to give me advice.

As for the code part, jQuery is used. In fact, there is no problem if it is not used. Both animation sliding and monitoring can be written in pure js, but since this is not the focus here, why not use jQuery? Successful people stand on the shoulders of giants, and we are not as good as jQuery (.・`ω´・)

Updated on 2015/11/13

Yes A classmate pointed out that the code did not have a sliding effect in QQ mobile browser and Opera mobile browser. I looked for the reason and found it probably was the reason mentioned in the post. So based on the tips in the post and the tips of a master classmate of that classmate, I did Made some changes. Mainly in the touchmove event, it is judged whether to block the default event based on the horizontal and vertical coordinate displacements, as follows:


// 横向位移大于纵向位移,阻止纵向滚动
if (Math.abs(delta.x) > Math.abs(delta.y)) {
  event.preventDefault();
}

2016/02/25 update

qq_25558115 classmate mentioned: "If we can provide you with the information that only one record can be swiped left, if you slide other records, the record with left swipe will be returned to the original position." So a simple implementation was carried out. The main ideas are as follows:


// 用一个变量记录上一次左滑的对象
var lastLeftObj;

// 在左滑发生的时候,判定上一个左滑的对象是否存在,若存在,且不是当前被左滑的对象,则将其右滑
// 同时,记录新的左滑对象
// 在右滑发生时,将上一个左滑对象清空
if (左滑) {
  pressedObj左滑
  lastLeftObj && lastLeftObj != pressedObj && lastLeftObj右滑
  lastLeftObj = pressedObj; // 记录上一个左滑的对象
} else if (右滑) {
  pressedObj右滑
  lastLeftObj = null; // 清空上一个左滑的对象
}

Updated on 2016/09/06

Modified according to the bug raised by classmate Ma Canfa:

Make a judgment when swiping right. Only when the object to be swiped right (pressedObj) is the object that was last left swiped (lastLeftObj), slide the object right and clear lastLeftObj.


if (pressedObj == lastLeftObj) {...}

According to girlyougo’s suggestion, add the function of “resetting the current left slide button when clicking in other areas except this row”. The idea is to determine pressedObj!=lastLeftObj at the end of the slide, that is, it is known that the clicked/slided object is another object:


##

// 点击除当前左滑对象之外的任意其他位置
if (lastLeftObj && pressedObj != lastLeftObj) {
  $(lastLeftObj).animate({marginLeft:"0"}, 500); // 右滑
  lastLeftObj = null; // 清空上一个左滑的对象
}

In fact, after adding the above functions, The bug mentioned earlier no longer exists. However, the part of the code that eliminates bugs is retained here.

The updated complete code is as follows:


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>左划出现删除按钮,右滑隐藏</title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
  // 设定每一行的宽度=屏幕宽度+按钮宽度
  $(".line-scroll-wrapper").width($(".line-wrapper").width() + $(".line-btn-delete").width());
  // 设定常规信息区域宽度=屏幕宽度
  $(".line-normal-wrapper").width($(".line-wrapper").width());
  // 设定文字部分宽度(为了实现文字过长时在末尾显示...)
  $(".line-normal-msg").width($(".line-normal-wrapper").width() - 280);

  // 获取所有行,对每一行设置监听
  var lines = $(".line-normal-wrapper");
  var len = lines.length; 
  var lastX, lastXForMobile;

  // 用于记录被按下的对象
  var pressedObj; // 当前左滑的对象
  var lastLeftObj; // 上一个左滑的对象

  // 用于记录按下的点
  var start;

  // 网页在移动端运行时的监听
  for (var i = 0; i < len; ++i) {
    lines[i].addEventListener(&#39;touchstart&#39;, function(e){
      lastXForMobile = e.changedTouches[0].pageX;
      pressedObj = this; // 记录被按下的对象 

      // 记录开始按下时的点
      var touches = event.touches[0];
      start = { 
        x: touches.pageX, // 横坐标
        y: touches.pageY // 纵坐标
      };
    });

    lines[i].addEventListener(&#39;touchmove&#39;,function(e){
      // 计算划动过程中x和y的变化量
      var touches = event.touches[0];
      delta = {
        x: touches.pageX - start.x,
        y: touches.pageY - start.y
      };

      // 横向位移大于纵向位移,阻止纵向滚动
      if (Math.abs(delta.x) > Math.abs(delta.y)) {
        event.preventDefault();
      }
    });

    lines[i].addEventListener(&#39;touchend&#39;, function(e){
      if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
        $(lastLeftObj).animate({marginLeft:"0"}, 500); // 右滑
        lastLeftObj = null; // 清空上一个左滑的对象
      }
      var diffX = e.changedTouches[0].pageX - lastXForMobile;
      if (diffX < -150) {
        $(pressedObj).animate({marginLeft:"-132px"}, 500); // 左滑
        lastLeftObj && lastLeftObj != pressedObj && 
          $(lastLeftObj).animate({marginLeft:"0"}, 500); // 已经左滑状态的按钮右滑
        lastLeftObj = pressedObj; // 记录上一个左滑的对象
      } else if (diffX > 150) {
       if (pressedObj == lastLeftObj) {
        $(pressedObj).animate({marginLeft:"0"}, 500); // 右滑
        lastLeftObj = null; // 清空上一个左滑的对象
       }
      }
    });
  }

  // 网页在PC浏览器中运行时的监听
  for (var i = 0; i < len; ++i) {
    $(lines[i]).bind(&#39;mousedown&#39;, function(e){
      lastX = e.clientX;
      pressedObj = this; // 记录被按下的对象
    });

    $(lines[i]).bind(&#39;mouseup&#39;, function(e){
      if (lastLeftObj && pressedObj != lastLeftObj) { // 点击除当前左滑对象之外的任意其他位置
        $(lastLeftObj).animate({marginLeft:"0"}, 500); // 右滑
        lastLeftObj = null; // 清空上一个左滑的对象
      }
      var diffX = e.clientX - lastX;
      if (diffX < -150) {
        $(pressedObj).animate({marginLeft:"-132px"}, 500); // 左滑
        lastLeftObj && lastLeftObj != pressedObj && 
          $(lastLeftObj).animate({marginLeft:"0"}, 500); // 已经左滑状态的按钮右滑
        lastLeftObj = pressedObj; // 记录上一个左滑的对象
      } else if (diffX > 150) {
       if (pressedObj == lastLeftObj) {
        $(pressedObj).animate({marginLeft:"0"}, 500); // 右滑
        lastLeftObj = null; // 清空上一个左滑的对象
       }
      }
    });
  }
});
</script>
<style type="text/css">
* { margin: 0; padding: 0; }
.line-wrapper { width: 100%; height: 144px; overflow: hidden; font-size: 28px; border-bottom: 1px solid #aaa; }
.line-scroll-wrapper { white-space: nowrap; height: 144px; clear: both; }
.line-btn-delete { float: left; width: 132px; height: 144px; }
.line-btn-delete button { width: 100%; height: 100%; background: red; border: none; font-size: 24px; font-family: &#39;Microsoft Yahei&#39;; color: #fff; }
.line-normal-wrapper { display: inline-block; line-height: 100px; float: left; padding-top: 10px; padding-bottom: 10px; }
.line-normal-icon-wrapper { float: right; width: 120px; height: 120px; margin-right: 12px; }
.line-normal-icon-wrapper img { width: 120px; height: 120px; }
.line-normal-avatar-wrapper { width: 100px; height: 124px; float: left; margin-left: 12px; }
.line-normal-avatar-wrapper img { width: 92px; height: 92px; border-radius: 60px; }
.line-normal-left-wrapper { float: left; overflow: hidden; }
.line-normal-info-wrapper { float: left; margin-left: 10px; }
.line-normal-user-name { height: 28px; line-height: 28px; color: #4e4e4e; margin-top: 7px; }
.line-normal-msg { height: 28px; line-height: 28px; overflow:hidden; text-overflow:ellipsis; color: #4e4e4e; margin-top: 11px; }
.line-normal-time { height: 28px; line-height: 28px; color: #999; margin-top: 11px; }
</style>
</head>
<body>
<p class="line-wrapper">
 <p class="line-scroll-wrapper">
  <p class="line-normal-wrapper">
   <p class="line-normal-left-wrapper">
    <p class="line-normal-avatar-wrapper"><img  src="/static/imghwm/default1.png"  data-src="1.jpg"  class="lazy"   / alt="jQuery implements the method of sliding left to appear delete button" ></p>
    <p class="line-normal-info-wrapper">
     <p class="line-normal-user-name">蜡笔小新</p>
     <p class="line-normal-msg">在同行的小伙伴中提到了你</p>
     <p class="line-normal-time">1分钟前</p>
    </p>
   </p>
   <p class="line-normal-icon-wrapper"><img  src="/static/imghwm/default1.png"  data-src="5.jpg"  class="lazy"  / alt="jQuery implements the method of sliding left to appear delete button" ></p>
  </p>
  <p class="line-btn-delete"><button>删除</button></p>
 </p>
</p>
<p class="line-wrapper">
 <p class="line-scroll-wrapper">
  <p class="line-normal-wrapper">
   <p class="line-normal-left-wrapper">
    <p class="line-normal-avatar-wrapper"><img  src="/static/imghwm/default1.png"  data-src="2.jpg"  class="lazy"   / alt="jQuery implements the method of sliding left to appear delete button" ></p>
    <p class="line-normal-info-wrapper">
     <p class="line-normal-user-name">乔巴</p>
     <p class="line-normal-msg">你看不到我哦</p>
     <p class="line-normal-time">1分钟前</p>
    </p>
   </p>
   <p class="line-normal-icon-wrapper"><img  src="/static/imghwm/default1.png"  data-src="6.jpg"  class="lazy"  / alt="jQuery implements the method of sliding left to appear delete button" ></p>
  </p>
  <p class="line-btn-delete"><button>删除</button></p>
 </p>
</p>
<p class="line-wrapper">
 <p class="line-scroll-wrapper">
  <p class="line-normal-wrapper">
   <p class="line-normal-left-wrapper">
    <p class="line-normal-avatar-wrapper"><img  src="/static/imghwm/default1.png"  data-src="3.jpg"  class="lazy"   / alt="jQuery implements the method of sliding left to appear delete button" ></p>
    <p class="line-normal-info-wrapper">
     <p class="line-normal-user-name">贱行贱远</p>
     <p class="line-normal-msg">回忆里想起模糊的小时候,云朵漂浮在蓝蓝的天空,那时的你说,要和我手牵手,一起走到时间的尽头</p>
     <p class="line-normal-time">1分钟前</p>
    </p>
   </p>
   <p class="line-normal-icon-wrapper"><img  src="/static/imghwm/default1.png"  data-src="7.jpg"  class="lazy"  / alt="jQuery implements the method of sliding left to appear delete button" ></p>
  </p>
  <p class="line-btn-delete"><button>删除</button></p>
 </p>
</p>
<p class="line-wrapper">
 <p class="line-scroll-wrapper">
  <p class="line-normal-wrapper">
   <p class="line-normal-left-wrapper">
    <p class="line-normal-avatar-wrapper"><img  src="/static/imghwm/default1.png"  data-src="4.png"  class="lazy"   / alt="jQuery implements the method of sliding left to appear delete button" ></p>
    <p class="line-normal-info-wrapper">
     <p class="line-normal-user-name">小黄人</p>
     <p class="line-normal-msg">哈哈哈哈哈……暑假来看小黄人电影哦~哈哈哈……</p>
     <p class="line-normal-time">1分钟前</p>
    </p>
   </p>
   <p class="line-normal-icon-wrapper"><img  src="/static/imghwm/default1.png"  data-src="8.jpg"  class="lazy"  / alt="jQuery implements the method of sliding left to appear delete button" ></p>
  </p>
  <p class="line-btn-delete"><button>删除</button></p>
 </p>
</p>
</body>
</html>

Summary

The code is still relatively rough, there are many bugs, and some places are not so absolute. For example, when I press it, it is on the first record, and then when I lift it, it is on the second record, then the slide will be on the first record at this time. But this depends on the specific needs. If you think the sliding object should be based on the object when it is pressed, then slide the object when it is pressed no matter where it is lifted; if you think the sliding object should be lifted It's okay if you don't slide any object if you think it's not the same object when you press it and lift it up. In short, it depends on the demand.

Related recommendations:

Based on JS to implement the function of sliding left on the mobile terminal to display the delete button

Example details Angular implements the function of displaying the input content at the top after clicking the button

WeChat applet implements the function of changing the font color by clicking the button

The above is the detailed content of jQuery implements the method of sliding left to appear delete button. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools