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

Pure CSS code to achieve flow and dynamic line effects

Ideas: An outer box sets the background; an inner...

Summary of basic usage of $ symbol in Linux

Linux version: CentOS 7 [root@azfdbdfsdf230lqdg1b...

Detailed explanation of docker command to backup linux system

tar backup system sudo tar cvpzf backup.tgz --exc...

Summary of some situations when Docker container disk is full

Preface This article describes two situations I h...

Recommend a cool interactive website made by a front-end engineer

Website link: http://strml.net/ By Samuel Reed Ti...

DIV background semi-transparent text non-translucent style

DIV background is semi-transparent, but the words ...

mysql 5.7.20 win64 installation and configuration method

mysql-5.7.20-winx64.zipInstallation package witho...

...

Summary of MySql index, lock, and transaction knowledge points

This article summarizes the knowledge points of M...

43 Web Design Mistakes Web Designers Should Watch Out For

This is an article about website usability. The a...

How to create a simple column chart using Flex layout in css

The following is a bar chart using Flex layout: H...