您的位置 首页 javascript教程

JavaScript如何实现鼠标左键拖拽效果

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

方式一:

<!DOCTYPE html><html><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>    </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>

相关视频教程推荐:《javascript高级教程

方式二:

<!DOCTYPE html><html><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>    </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>

相关推荐下载:《文字特效

以上就是JavaScript如何实现鼠标左键拖拽效果的详细内容,更多请关注php中文网其它相关文章!

文章来源:火云技术网

文章标题:JavaScript如何实现鼠标左键拖拽效果

文章地址:https://www.pyhw.net/31854_javascript%e5%a6%82%e4%bd%95%e5%ae%9e%e7%8e%b0%e9%bc%a0%e6%a0%87%e5%b7%a6%e9%94%ae%e6%8b%96%e6%8b%bd%e6%95%88%e6%9e%9c.html

关于作者: 火云技术网

热门文章

发表评论

您的电子邮箱地址不会被公开。

网站地图