本文實例為大家分享了js實現(xiàn)窗口拖拽的具體代碼,供大家參考,具體內(nèi)容如下
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box { height: 300px; width: 300px; background-color: green; position: absolute; } </style> </head> <body> <div id="box"> </div> </body> <script type="text/javascript"> var box = document.getElementById("box"); //鼠標按下的函數(shù) box.onmousedown = function(ev) { var oEvent = ev || event; //求出鼠標和box的位置差值 var x = oEvent.clientX - box.offsetLeft; var y = oEvent.clientY - box.offsetTop; //鼠標移動的函數(shù) //把事件加在document上,解決因為鼠標移動太快時, //鼠標超過box后就沒有了拖拽的效果的問題 document.onmousemove = function(ev) { var oEvent = ev || event; //保證拖拽框一直保持在瀏覽器窗口內(nèi)部,不能被拖出的瀏覽器窗口的范圍 var l = oEvent.clientX - x; var t = oEvent.clientY - y; if(l < 0) { l = 0; } else if(l > document.documentElement.clientWidth - box.offsetWidth) { l = document.documentElement.clientWidth - box.offsetWidth; } if(t < 0) { t = 0; } else if(t > document.documentElement.clientHeight - box.offsetHeight) { t = document.documentElement.clientHeight - box.offsetHeight; } box.style.left = l + "px"; box.style.top = t + "px"; } //鼠標抬起的函數(shù) document.onmouseup = function() { document.onmousemove = null; document.onmouseup = null; } //火狐瀏覽器在拖拽空div時會出現(xiàn)bug //return false阻止默認事件,解決火狐的bug return false; } </script> </html>以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答