<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box { height: 300px; width: 300px; background-color: gre ...
<!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>