使用JS鼠标事件写拖拽功能时除了使用if判断边界外是否还有其他方法求指教,下面是我是用面向过程来写的一个。
<!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>