这篇文章主要介绍了js是如何实现盒子拖拽动画效果的,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。
具体代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.wrap {
width: 400px;
height: 200px;
border: 1px solid #ccc;
border-right-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -100px;
box-sizing: border-box;
}
.wrap .head {
height: 40px;
padding-left: 4px;
padding-right: 4px;
background-color: #ccc;
box-sizing: border-box;
line-height: 40px;
user-select: none;
}
.head:hover {
cursor: move;
}
.head span {
float: left;
}
#close {
float: right;
}
#close:hover {
cursor: pointer;
}
</style>
</head>
<body>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<p>tom</p>
<div class="wrap">
<div class="head">
<span>试着拖拽我</span>
<span id="close">【关闭】</span>
</div>
</div>
<script>
let wrap = document.querySelector('.wrap');
let close = document.getElementById('close');
let head = document.querySelector('.head');
head.onmousedown = function (e) {
// 获得鼠标在 head 中的坐标
let x = e.pageX - wrap.offsetLeft;
let y = e.pageY - wrap.offsetTop;
console.log(x, y);
document.onmousemove = function (e) {
let xx = e.pageX - x;
let yy = e.pageY - y;
// 设置边界限制
xx = xx < 0 ? 0 : xx;
yy = yy < 0 ? 0 : yy;
if (xx >= innerWidth - wrap.offsetWidth) {
document.documentElement.scrollLeft = 20;
} else {
document.documentElement.scrollLeft = 0;
}
xx = xx > innerWidth - wrap.offsetWidth ? innerWidth-wrap.offsetWidth : xx;
yy = yy > innerHeight - wrap.offsetHeight + document.documentElement.scrollTop ? innerHeight - wrap.offsetHeight + document.documentElement.scrollTop : yy;
wrap.style.left = xx + 'px';
wrap.style.top = yy + 'px';
// 禁止X滚动轴
document.body.style.overflowX = 'hidden';
wrap.style.marginLeft = 0;
wrap.style.marginTop = 0;
};
};
document.onmouseup = function () {
document.onmousemove = null;
};
close.onclick = function () {
wrap.style.display = 'none';
};
</script>
</body>
</html>
实现效果:
感谢你能够认真阅读完这篇文章,希望小编分享js是如何实现盒子拖拽动画效果的内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。