Home >Web Front-end >JS Tutorial >Simple implementation of JS drag effect

Simple implementation of JS drag effect

不言
不言Original
2018-03-31 13:36:231164browse

This article shares with you the code for simply realizing the JS drag effect, which is implemented using the mobile attribute of Trnsform of CSS3. Friends in need can take a look at the content of this article

Achieved by using the mobile attribute of CSS3 Trnsform.

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>

Related recommendations:

Simple implementation of JSP paging display effect

How to implement Image compression method in JS

How to implement the exquisite automatic currying function in JS

The above is the detailed content of Simple implementation of JS drag effect. 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