欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

13.JavaScript实现鼠标左键拖拽效果

程序员文章站 2022-04-15 22:59:09
实现鼠标左键拖拽效果的两种方式: 方式一:

实现鼠标左键拖拽效果的两种方式:

方式一:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document</title>
    <style>
        .move {
            width: 100px;
            height: 100px;
            background: red;
            border-radius: 50%;
            position:absolute;
            left:0;
            top:0;
        }
    </style>
</head>

<body>
    <div class="move">

    </div>
    <script>
        //制作一个鼠标左键拖拽效果
        var div = document.getelementsbyclassname("move")[0];
        var style = window.getcomputedstyle(div);
        var divleft = parsefloat(style.left);
        var divtop = parsefloat(style.top);
        div.onmousedown = function(e){
            if(e.button !== 0){
                return ;//不是鼠标左键,return
            }
            window.onmousemove = function(e){
                divleft += e.movementx;//距上次鼠标位置的x长度
                divtop += e.movementy;//距上次鼠标位置的y长度
                div.style.left = divleft + "px";
                div.style.top = divtop + "px";
            }
            window.onmouseup = window.onmouseleave = function(){
                if(e.button === 0){//鼠标左键
                    window.onmousemove = null;
                }
            }
        }
    </script>
</body>

</html>

 

方式二:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>document</title>
    <style>
        .move {
            width: 100px;
            height: 100px;
            background: red;
            border-radius: 50%;
            position:absolute;
            left:0;
            top:0;
        }
    </style>
</head>

<body>
    <div class="move">

    </div>
    <script>
        //制作一个鼠标左键拖拽效果
        var div = document.getelementsbyclassname("move")[0];
        var style = window.getcomputedstyle(div);
        div.onmousedown = function(e){
            if(e.button !== 0){
                return ;//不是鼠标左键,return
            }
            var divleft = parsefloat(style.left);
            var divtop = parsefloat(style.top);
            var divpagex = e.pagex;
            var divpagey = e.pagey;
            window.onmousemove = function(e){
                var disx = e.pagex - divpagex;
                var disy = e.pagey - divpagey;
                div.style.left = divleft + disx + "px";
                div.style.top = divtop + disy + "px";
            }
            window.onmouseup = window.onmouseleave = function(){
                if(e.button === 0){//鼠标左键
                    window.onmousemove = null;
                }
            }
        }
    </script>
</body>

</html>