原生js实现div在窗口内移动
css样式
<style>
*{margin:0;padding:0;}
#div1{
position: absolute;
width: 490px;
height: 40px;
z-index: 10;
background-color: aliceblue;
cursor: move;
}
#contents{
position: absolute;
width: 700px;
height: 470px;
top: 50%;
left: 50%;
margin-top: -235px;
margin-left: -350px;
display: none;
}
</style>
html
<body>
<div id="contents">
<div id="div1"></div>
</div>
</body>
js代码
<script>
window.onload = function () {
var Content = document.getElementById("contents");
var Odiv = document.getElementById("div1");
var disX = 0;
var disY = 0;
Odiv.onmousedown = function (ev) {
//鼠标事件对象
var oEvent = ev || event;
disX = oEvent.clientX - Content.offsetLeft;
disY = oEvent.clientY - Content.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 - Content.offsetWidth) {
l = document.documentElement.clientWidth - Content.offsetWidth;
}
if (t < 50) {
t = 0;
}
else if (t > document.documentElement.clientHeight - Content.offsetHeight) {
t = document.documentElement.clientHeight - Content.offsetHeight;
}
Content.style.left = l+ "px";
Content.style.top = t + "px";
Content.style.cursor = "move";
/**如果父盒子设置有marginTop和marginLeft则需要将其设置为0*/
Content.style.marginLeft = 0;
Content.style.marginTop =0;
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
Content.style.cursor = "auto";
}
//阻止默认事件
return false;
}
}
</script>