拖拽效果
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>拖拽效果</title> <link rel="stylesheet" type="text/css" href="拖拽效果.css"> </head> <body> <div id="box"> <h1 id="heading">点击拖拽</h1> </div> <script src="拖拽效果.js"></script> </body> </html>
CSS
#box { width:300px; height:300px; background-color:red; padding:10px; border:5px solid green; text-align: center; position:absolute; top:50px; left:50px; } #heading { background-color: blue; }
JavaScript
//页面加载完毕之后调用drag函数 window.onload = drag; //封装drag函数 function drag() { //获取heading元素 var heading = document.getElementById("heading"); //鼠标在heading元素区域按下时执行fnDown函数 heading.onmousedown = fnDown; //鼠标在页面中松开时取消拖拽效果 document.onmouseup = function() { document.onmousemove = null; }; }; //封装fnDown函数 function fnDown(event) { event = event || window.event; var box = document.getElementById("box"), heading = document.getElementById("heading"), //取得鼠标点击的那个点与box左上角的距离 disY = event.clientY - box.offsetTop, disX = event.clientX - box.offsetLeft; //鼠标在页面中移动时执行匿名函数 document.onmousemove = function(event) { event = event || window.event; //核心思想是:鼠标在哪儿,box跟到哪儿 //计算box距离页面左上角的距离 var t = event.clientY - disY, l = event.clientX - disX, window_width = document.documentElement.clientWidth || document.body.clientWidth, window_height = document.documentElement.clientHeight || document.body.clientHeight, max_t = window_height - box.offsetHeight, max_l = window_width - box.offsetWidth; //控制box移动的最大最小距离 if(t < 0) { t = 0; } else if(t > max_t) { t = max_t; }; if(l < 0) { l = 0; } else if(l > max_l) { l = max_l; }; //box的位置跟随鼠标光标 box.style.top = t + "px"; box.style.left = l + "px"; }; };
时间: 2024-12-09 17:43:17