让子元素在父元素边界内移动

位置: 首页 > 前端三套件
[发布: 2023.7.28  作者: 马黑  阅读: 159]

移动子元素的方法:单击子元素,子元素就会跟随鼠标指针走,再单击它,解除跟屁虫属性。

实现原理:借助 e.clientX/Y 和 getBoundingClientRect() 方法,基于浏览器视口进行计算,确保子元素在父元素的边界内移动。e.clientX/Y 实时返回鼠标指针基于浏览器视口的xy坐标值(尽管 e 基于特定元素),getBoundingClientRect() 以对象的形式返回指定元素的 X、Y、left、top、bottom 和 width、height 等无单位的像素值。下面是具体代码:
<style>
#mum {
    margin: 20px auto;
    width: 600px;
    height: 300px;
    border: 1px solid gray;
    position: relative;
}
#son {
    width: 40px;
    height: 40px;
    left: 10px;
    top: 10px;
    background: pink;
    position: absolute;
}
</style>

<div id="mum">
    <div id="son"></div>
</div>

<script>
let canmove = false, rtMum = mum.getBoundingClientRect(), rtSon = son.getBoundingClientRect();
son.onclick = () => canmove = !canmove;
mum.onmousemove = (e) => {
    if(canmove) {
    	let Left = e.clientX - rtMum.left - rtSon.width / 2;
    	if(Left < 0) Left = 0;
    	if(Left > rtMum.width - rtSon.width) Left = rtMum.width - rtSon.width;
    	let Top = e.clientY - rtMum.top - rtSon.height / 2;
    	if(Top < 0) Top = 0;
    	if(Top > rtMum.height - rtSon.height) Top = rtMum.height - rtSon.height;
    	son.style.left = Left + 'px';
    	son.style.top = Top + 'px';
    }
};
</script>

前一篇: lrc歌词同步实现原理展示
下一篇: CSS :文本对齐演示

发表评论:

  
 

评论列表 [1条]

#1 | 飞飞 于 2023-7-29 08:18 发布: 这个好玩,有指挥棒。。。

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com