<!DOCTYPE html>
<html lang="en">
<style>
.smallBox {
width: 500px;
height: 500px;
position: relative;
background-color: antiquewhite;
margin: 30px 30px;
}
.smallBoxItem {
position: absolute;
/* 添加绝对定位,让box相对于页面可移动 */
top: 30px;
left: 30px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box" draggable="true">
<div class='smallBox'>
<div class='smallBoxItem' draggable="true"></div>
</div>
</div>
<script>
var smallBoxItem = document.querySelector(".smallBoxItem");
var smallBox = document.querySelector(".smallBox");
// 开始拖拽
smallBoxItem.ondragstart = function () {
// 记录鼠标与盒子之间的距离
mouse = {
x: event.offsetX,
y: event.offsetY
}
}
smallBoxItem.ondrag = function () {
//拖拽的时候 smallBoxItem透明度改变
let w = smallBox.offsetWidth - (event.pageX + smallBoxItem.offsetWidth) > 0 ? smallBox.offsetWidth - (event.pageX + smallBoxItem.offsetWidth) : 0
event.target.style.opacity = w / smallBox.offsetWidth;
}
// 拖拽结束
smallBoxItem.ondragend = function () {
// 盒子的位置 = 鼠标与页面之间的距离 - 鼠标与盒子之间的距离
let left = event.pageX - mouse.x
let top = event.pageY - mouse.y
//smallBoxItem 拖拽不超过smallBox便捷
if (left < 0) {
left = 0
} else if (left > smallBox.offsetWidth - smallBoxItem.offsetWidth) {
left = smallBox.offsetWidth - smallBoxItem.offsetWidth
}
if (top < 0) {
top = 0
} else if (top > smallBox.offsetHeight - smallBoxItem.offsetHeight) {
top = smallBox.offsetHeight - smallBoxItem.offsetHeight
}
smallBoxItem.style.left = left + "px";
smallBoxItem.style.top = top + "px";
}
</script>
</html>
js 拖拽drag
最新推荐文章于 2024-04-04 02:06:01 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)