Home > Web Front-end > JS Tutorial > A simple way to implement JS drag effect

A simple way to implement JS drag effect

小云云
Release: 2018-03-31 16:53:20
Original
2134 people have browsed it

This article mainly shares with you a simple method to achieve JS drag effect, which is achieved by using the mobile attribute of Trnsform of CSS3. I hope it can help everyone.

The code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
      #dom{
          width: 50px;
          height: 50px;
          border: 2px solid red;
      }
    </style>
</head>
<body>
    <p id="dom"></p>
    <script>

        (function(){
            let dom = document.getElementById(&#39;dom&#39;);
            let moveX,moveY
            dom.addEventListener(&#39;mousedown&#39;,function (e) { 
                moveX=e.target.offsetWidth;
                moveY=e.target.offsetHeight
                console.log(e);
                document.addEventListener(&#39;mousemove&#39;,move,false)
                
            })
            function move(e){
                if(moveY&& moveY){
                    let width =moveX/2,height = width+moveY;
                    dom.style.transform=&#39;translate(&#39;+(e.x-width)+&#39;px,&#39;+(e.y-height)+&#39;px)&#39;
                }
            }
            document.addEventListener(&#39;mousemove&#39;,move,false)
            document.addEventListener(&#39;mouseup&#39;,function (e) {
                let width =moveX/2,height = width+moveY;
                let i =(e.x-width) +&#39;px&#39;,y=(e.y-height)+&#39;px&#39;;
              
                if(moveX && moveY){
                    document.removeEventListener(&#39;mousemove&#39;,move,false);
                    dom.style.transform=&#39;translate(&#39;+i+&#39;,&#39;+y+&#39;)&#39;;
                    moveY=&#39;&#39;,moveX=&#39;&#39;
                }
                
            })
        })()
    
    
    </script>
</body>
</html>
Copy after login

Related recommendations:

JS drag effect implementation code is relatively simple_javascript skills

The above is the detailed content of A simple way to implement JS drag effect. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template