Native JS to achieve sliding button effect

Native JS to achieve sliding button effect

The specific code of the sliding button made with Js is for your reference. The specific content is as follows

First paste the effect picture

Paste the source code again

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div style="position: relative;width:100vw;height:100vh">
        <div id="container">
            <svg style="width:inherit;height:inherit">
                <circle id="c" cx="25" cy="25" r="23" style="fill:white; stroke:gray; stroke-width:2;"
                
                onmousedown="down(event)"
                onmouseup="up(event)"
                onmouseleave="up(event)"
               />
            </svg>
        </div>
         </div>
         <!-- <script>
             setTimeout(function () {
                let c = document.querySelector('circle');
                console.log(c.parentNode.parentNode.style)
                 
               },500)
            
         </script> -->
  
  <style>
      body{
          margin:0;
          background-color:azure;
      }
      #container{
          position:absolute;
          left: 50%; top: 50%; 
          transform: translateX(-50%) translateY(-50%);
          width: 200px;
          height: 50px;
          background-color: black;
          border-radius: 50px;
      }
      
  </style>
  <script>
      let circle = document.getElementById('c'),
          clicked = false,
       
          x = 0,y = 0;
          
      circle.addEventListener("mousemove",function(e){
      x = e.offsetX;
      
      
      if(clicked){

          circle.setAttribute("cx",x)
      }

      
      })
      function t(e){
        circle.setAttribute("cx",e.offsetX);
      }
      function down(e){
       clicked = true;
      }
      function up(){
      if(clicked){
          let flag;
     if(x <= 100)
      new Promise(function(resolve,reject){
     flag = setInterval(function(){
          x -= 2;

          circle.setAttribute("cx",x);
          if(x <= 25){

              circle.setAttribute("cx",25)
              circle.setAttribute("style","fill:white; stroke:gray; stroke-width:2;")
              resolve("ok")
          }
      })
      }).then(res => {
        clearInterval(flag)
      })
      else 
      new Promise(function(resolve,reject){
     flag = setInterval(function(){
          x += 2;
          circle.setAttribute("cx",x);
          if(x >= 175){
              circle.setAttribute("cx",175);
              circle.setAttribute("style","fill:black; stroke:gray; stroke-width:2;")
              resolve("ok")
          }
      })
      }).then(res => {
        clearInterval(flag)
      })
      }
      clicked = false;
      
      }
     
  </script>
    
</body>
</html>

Knowledge points, production ideas and steps

1. Basic layout ( parent and child , left: 50%; top: 50%; transform: translateX(-50%)
translateY(-50%);)

2. The circle (cx) of svg controls the movement, and the cx of the circle is controlled by setAtrribute .

3. **Promise.then()** is used to ensure clearInterval after completion

4. circle listens to mousemove, mouseup, and mousedown events. When the mousedown event is triggered, cliked will be set to true and the move event will be reset;

5. mouseup and mouseleave will set cliked to false, thus failing to trigger the reset (stop) of the move event;

6. When in the stopped state, determine whether the origin is on the left or right side. Animation: If it is in the left half, use setInterval to move 1.5px each time for 10ms per frame, and stop when it reaches the start or end point.

7. Then switch the style.

All the codes are original by me, please feel free to copy them. The codes have not been sorted out and there may be invalid variables. They just represent my ideas.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • How to implement JS to delete the favorites button by sliding right on the encapsulated list
  • Based on JS, the delete button function appears when sliding left on the mobile terminal
  • js imitates the operation of sliding left on a contact and sliding out the delete button in QQ
  • js realizes the sliding effect of the button by changing the display style of the button

<<:  Detailed explanation of the calculation method of flex-grow and flex-shrink in flex layout

>>:  The benefits and examples of placing the site map at the bottom of the web page

Recommend

A very detailed explanation of Linux C++ multi-thread synchronization

Table of contents 1. Mutex 1. Initialization of m...

How to implement online hot migration of KVM virtual machines (picture and text)

1. KVM virtual machine migration method and issue...

Use shell script to install python3.8 environment in CentOS7 (recommended)

One-click execution To install Python 3.8 in a vi...

Detailed explanation of execution context and call stack in JavaScript

Table of contents 1. What is the execution contex...

JavaScript implements click toggle function

This article example shares the specific code of ...

Detailed explanation of grep and egrep commands in Linux

rep / egrep Syntax: grep [-cinvABC] 'word'...

Summary of shell's method for determining whether a variable is empty

How to determine whether a variable is empty in s...

Discussion on Web Imitation and Plagiarism

A few months after entering the industry in 2005, ...

HTML table markup tutorial (15): table title

<br />This tag can be used to directly add a...

Docker image loading principle

Table of contents Docker images What is a mirror?...

Some key points of website visual design

From handicraft design to graphic design to web de...

Summary of methods to clear cache in Linux system

1) Introduction to cache mechanism In the Linux s...