小练习:
写了一个可拖拽元素,按住顶部工具条可拖动至任意位置,但不能超出浏览器边框,按照这几个步骤完成即可,并配图食用更好理解
- 记录鼠标按下的坐标,就是⚪的坐标
-
获取该元素的坐标 ,即算出矩形距离左边、顶部距离(ex,ey)
-
鼠标按下后,监听整个屏幕的鼠标移动,可根据抬起点位坐标(e.clientX,e.clientY)计算出鼠标移动的距离
-
移动到新位置,计算该元素至浏览器左边距离,用初始位置距离左边距离ex加上移动距离disX,计算该元素至浏览器顶部距离同理
-
鼠标抬起后,不再监听鼠标移动和抬起,监听事件设置为null
html文件如下
<!DOCTYPE html>
<div class="item">
<div class="tips-Wrapper">
<div class="top"></div>
<div class="bottom">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsum est temporibus doloremque eos inventore, doloribus aspernatur eius numquam provident optio voluptate quos asperiores cupiditate ducimus neque iste perferendis ab sed?</div>
</div>
</div>
<script src="./index.js">
</script>
</html>
<style lang="less" scoped>
.item{
width: 100%;
height: 100%;
position: relative;
}
.tips-Wrapper{
position: absolute;
width: 400px;
height: 350px;
background: #dedede;
}
.top{
height: 28px;
background: rgb(199, 235, 243,0.3);
}
.bottom{
height: calc(100% - 28px);
background:rgba(249, 253, 253, 0.847);
color: rgba(59, 56, 52, 0.426);
padding: 15px;
/* text-align: justify; */
}
</style>
index.js文件如下
var moveArea = document.getElementsByClassName('top')[0];
var note = document.getElementsByClassName('tips-Wrapper')[0];
//一开始保存至变量,用变量不会导致重排,用属性会导致重排
moveArea.onmousedown = function (e) {
console.log('onmousedown', e);
//记录鼠标按下的坐标
var x = e.clientX;
var y = e.clientY;
var rect = moveArea.getBoundingClientRect();
//该元素的坐标
var ex = rect.left;
var ey = rect.top;
console.log('rect', rect);
//获取视口宽高、元素宽高
var w = document.documentElement.clientWidth,
h = document.documentElement.clientHeight;
var ew = note.offsetWidth,
eh = note.offsetHeight;
//算出最大的left top
var maxLeft = w - ew;
var maxTop = h - eh;
//鼠标按下后,监听整个屏幕的鼠标移动
window.onmousemove = function (e) {
console.log('onmousemove', e);
var disX = e.clientX - x;
var disY = e.clientY - y;
var left = ex + disX;
var top = ey + disY;
if (left < 0) {
left = 0;
}
if (left > maxLeft) {
left = maxLeft;
}
if (top < 0) {
top = 0;
}
if (top > maxTop) {
top = maxTop;
}
console.log('note', note);
note.style.left = left + 'px';
note.style.top = top + 'px';
};
//鼠标抬起后,不再监听鼠标移动和抬起
window.onmouseup = function (e) {
console.log('onmouseup', e);
window.onmousemove = null;
window.onmouseup = null;
};
};