JS完美拖拽
Posted 风致﹏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS完美拖拽相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box{
height: 100px;
width: 100px;
background:red;
position: absolute;
cursor:move;
}
</style>
</head>
<body>
<div id="box">
</div>
</body>
</html>
<script>
var oBox = document.querySelector("#box");
oBox.onmousedown = function(evt){
var e = evt || event;
var offsetX = e.offsetX;
var offsetY = e.offsetY;
document.onmousemove = function(evt){
var e = evt || event;
var x = e.pageX - offsetX;
var y = e.pageY - offsetY;
if(x<0){
x = 0;
}
var maxLeft = window.innerWidth - oBox.offsetWidth;
if(x > maxLeft){
x = maxLeft;
}
if(y<0){
y = 0;
}
var maxTop = window.innerHeight - oBox.offsetHeight;
if(y > maxTop){
y = maxTop;
}
oBox.style.left = x + "px";
oBox.style.top = y + "px";
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
以上是关于JS完美拖拽的主要内容,如果未能解决你的问题,请参考以下文章