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: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools