本文實例為大家分享了js實現窗口拖拽的具體代碼,供大家參考,具體內容如下
<!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");
//鼠標按下的函數
box.onmousedown = function(ev) {
var oEvent = ev || event;
//求出鼠標和box的位置差值
var x = oEvent.clientX - box.offsetLeft;
var y = oEvent.clientY - box.offsetTop;
//鼠標移動的函數
//把事件加在document上,解決因為鼠標移動太快時,
//鼠標超過box後就沒有了拖拽的效果的問題
document.onmousemove = function(ev) {
var oEvent = ev || event;
//保證拖拽框一直保持在浏覽器窗口內部,不能被拖出的浏覽器窗口的范圍
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";
}
//鼠標抬起的函數
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
//火狐浏覽器在拖拽空div時會出現bug
//return false阻止默認事件,解決火狐的bug
return false;
}
</script>
</html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。