要求实现一个子p只能在父p中拖动,现效果已实现,可是有个问题是当我将mousemove和mouseup绑定在child上时,只能实现一次拖拽,而将其绑定在document上时,便可实现随意拖拽。为什么绑定在child上就只能拖拽一次呢?代码如下:
<head lang="en">
<meta charset="UTF-8">
<title>父元素内拖拽</title>
</head>
<style>
#parent{
width: 300px;
height: 300px;
background-color:lightskyblue;
position: relative;
}
#child{
width: 100px;
height: 100px;
background-color:hotpink;
position: absolute;
cursor: pointer;
}
</style>
<body>
<p id ="parent">
<p id ="child"></p>
</p>
</body>
window.onload = function(event){
var parent = document.getElementById("parent");
var child = document.getElementById("child");
var disX = 0; //鼠标按下时相对父元素的距离
var disY = 0;
child.onmousedown = function(event){
var event = event||window.event;
disX = event.clientX - child.offsetLeft;
disY = event.clientY - child.offsetTop;
document.onmousemove = function(event){
var event =event||window.event;
var l = event.clientX - disX;
var t = event.clientY - disY;
if(l < 0){
l = 0;
}else if(l > parent.offsetWidth - child.offsetWidth){
l = parent.offsetWidth - child.offsetWidth;
}
if(t < 0){
t = 0;
}else if(t > parent.offsetHeight - child.offsetHeight){
t = parent.offsetHeight - child.offsetHeight;
}
//css定位
child.style.left = l +'px';
child.style.top =t + 'px';
};
document.onmouseup = function(event){
document.onmousedown = null;
document.onmousemove = null;
};
};
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
欢迎选择我的课程,让我们一起见证您的进步~~