原生js實現div在窗口內移動
css樣式
<style>
*{margin:0;padding:0;}
#div1{width:200px;height:200px;position:absolute;left:500px;background:red;}
</style>
html
<body>
<div id="div1"></div>
</body>
js代碼
<script>
window.onload = function () {
var Odiv = document.getElementById("div1");
var disX = 0;
var disY = 0;
Odiv.onmousedown = function (ev) {
//鼠標事件對象
var oEvent = ev || event;
disX = oEvent.clientX - Odiv.offsetLeft;
disY = oEvent.clientY - Odiv.offsetTop;
document.onmousemove = function (ev) {
//鼠標事件對象
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
if (l < 50) {
l = 0;
}
else if (l > document.documentElement.clientWidth - Odiv.offsetWidth) {
l = document.documentElement.clientWidth - Odiv.offsetWidth;
}
if (t < 50) {
t = 0;
}
else if (t > document.documentElement.clientHeight - Odiv.offsetHeight) {
t = document.documentElement.clientHeight - Odiv.offsetHeight;
}
Odiv.style.left = l+ "px";
Odiv.style.top = t + "px";
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
//阻止默認事件
return false;
}
}
</script>