JS实现鼠标按下拖拽效果
程序员文章站
2024-01-08 16:44:52
原生js实现鼠标按下拖拽效果,供大家参考,具体内容如下
原生js实现鼠标按下拖拽效果,供大家参考,具体内容如下
<!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>鼠标拖动</title> <style type="text/css"> body { margin: 0; } div { width: 200px; height: 200px; position: absolute; background-color: pink; } </style> </head> <body> <div onmousedown="downdiv(this)" onmousemove="movediv(this)" onmouseup="updiv(this)"> </div> <script> //定义变量储存div的宽高 var obj_w, obj_h; //定义一个变量判断是否执行移动函数 var mousedown = false; //鼠标按下函数 function downdiv(obj) { //获取div的宽高 obj_w = obj.offsetwidth; obj_h = obj.offsetheight; //鼠标 var e = event || window.event; //e.clientx/y 是获取鼠标相对浏览器的位置;将div中心自动居中到鼠标 obj.style.left = (e.clientx - obj_w / 2) + "px"; obj.style.top = (e.clienty - obj_h / 2) + "px"; console.log(obj.style.left, obj.style.top) //按下时为ture,松开时为false,以判断是否执行执行mouvediv mousedown = true; } //鼠标移动函数 function movediv(obj) { obj_w = obj.offsetwidth; obj_h = obj.offsetheight; var e = event || window.event; console.log(e.clientx, e.clienty); console.log(obj_w, obj_h); if (mousedown) { obj.style.left = (e.clientx - obj_w / 2) + "px"; obj.style.top = (e.clienty - obj_h / 2) + "px"; console.log(obj.style.left, obj.style.top) } } //鼠标松开函数 function updiv(obj) { mousedown = false; } </script> </body> </html>
更多精彩文章请点击专题: javascript拖拽特效汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。