getBoundingClientRect()出现异常的原因是什么?
问题分析与解决
核心问题1:事件目标不稳定
你代码里用e.target.getBoundingClientRect(),但e.target会随鼠标位置变化——当鼠标移到div_moving上时,target就变成了这个移动的元素,而非父容器parent_div,导致获取的rect.top不是父容器的顶部位置,计算出的y值自然错误。
核心问题2:元素定位规则缺失
要让div_moving的top属性相对于父容器生效,必须给父容器parent_div设置position: relative,同时给div_moving设置position: absolute,否则top会相对于整个文档计算,位置必然跑偏。
修正后的完整代码
JavaScript部分
var div_moving = document.getElementById('div_moving'); var parent_div = document.getElementById('parent_div'); // 直接获取DOM元素,避免重复查询 var movingDiv = { getCoords: function(e) { // 固定取父容器的位置,而非e.target var rect = parent_div.getBoundingClientRect(); // e.clientY是鼠标在视口内的Y坐标,减去父容器视口顶部位置,得到相对父容器的Y值 var y = e.clientY - rect.top; return y; } }; parent_div.addEventListener('mousemove', function(e){ var result = movingDiv.getCoords(e); div_moving.style.top = result +'px'; div_moving.style.display = "initial"; }); parent_div.addEventListener('mouseleave', function(){ div_moving.style.display = "none"; });
CSS关键补充
#parent_div { position: relative; /* 必须设置,让子元素绝对定位以它为参照 */ /* 保留你原有其他样式 */ } #div_moving { position: absolute; /* 绝对定位,才能让top属性相对于父容器生效 */ /* 保留你原有其他样式 */ }
关键知识点说明
getBoundingClientRect()返回元素相对于浏览器视口的位置,搭配e.clientY(视口内鼠标Y坐标)计算,能准确得到鼠标在父容器内部的相对位置。- 事件绑定在父容器上时,直接使用父容器的DOM对象获取位置,避免依赖
e.target,可以规避事件冒泡导致的目标元素变化问题。
内容的提问来源于stack exchange,提问作者pilotnik
相关产品推荐
相关产品推荐

