技术问询:如何在class为earth的div完全左移时触发alert且不使用jQuery
实现div完全左移至100%位置时触发alert的方案(无jQuery)
嘿,这个需求我刚好有挺靠谱的实现思路!咱们完全可以不用定时器,靠位置检测或者CSS动画/过渡的事件监听来搞定,精准又不依赖时间,完美符合你的要求~
场景1:手动通过JS修改元素位置(比如动态调整left值)
这种情况下,我们可以用requestAnimationFrame配合getBoundingClientRect()来实时检测元素位置——requestAnimationFrame会和浏览器的刷新频率同步,比setTimeout精准得多,而且性能更好。
实现步骤:
- 获取目标元素
.earth - 定义检测函数,通过
getBoundingClientRect()获取元素的边界信息,判断是否完全移出左侧视口(当元素的右边界≤视口左边界时,说明元素完全在视口左边,也就是你说的“左移至100%位置”) - 用
requestAnimationFrame循环检测,满足条件时触发alert并停止检测
代码示例:
const earth = document.querySelector('.earth'); let animationId; function checkEarthPosition() { const elementRect = earth.getBoundingClientRect(); // 判断元素是否完全移出左侧视口 if (elementRect.right <= 0) { alert('元素已经完全左移到位啦!'); cancelAnimationFrame(animationId); // 停止检测,避免重复触发 } else { animationId = requestAnimationFrame(checkEarthPosition); // 继续下一次检测 } } // 启动位置检测 animationId = requestAnimationFrame(checkEarthPosition); // 假设你是这样触发元素左移的(示例): // earth.style.left = '-100%';
场景2:用CSS过渡/动画实现元素移动
如果你的元素是通过CSS过渡(transition)或动画(animation)来移动的,那直接监听对应的结束事件就更高效了,不用循环检测!
方法A:CSS过渡(transition)
先写CSS过渡样式:
.earth { position: relative; left: 0; /* 定义过渡动画 */ transition: left 1s ease-in-out; } /* 触发左移的类 */ .earth.move-completely-left { left: -100%; /* 如果元素占满视口,用-100vw更准确,根据实际布局调整 */ }
然后JS监听过渡结束事件:
const earth = document.querySelector('.earth'); earth.addEventListener('transitionend', (e) => { // 确保是left属性的过渡结束(避免其他属性过渡干扰) if (e.propertyName === 'left') { // 额外做一次位置校验,防止过渡中途被打断的情况 const rect = earth.getBoundingClientRect(); if (rect.right <= 0) { alert('元素完全左移到位!'); } } }); // 触发左移 earth.classList.add('move-completely-left');
方法B:CSS动画(animation)
先写CSS动画:
@keyframes slideToLeft { from { left: 0; } to { left: -100%; } /* 同样,根据布局调整为-100vw等值 */ } .earth { position: relative; } /* 触发动画的类 */ .earth.animate-left { animation: slideToLeft 1s forwards; /* forwards让动画结束后保持最终状态 */ }
然后JS监听动画结束事件:
const earth = document.querySelector('.earth'); earth.addEventListener('animationend', () => { const rect = earth.getBoundingClientRect(); if (rect.right <= 0) { alert('动画完成,元素完全左移!'); } }); // 启动动画 earth.classList.add('animate-left');
为什么不用setTimeout?
因为不同设备的性能、浏览器的渲染情况都不一样,动画/移动的实际耗时可能和你设定的时间有偏差,基于位置的判断完全依赖元素的实际状态,不会出现提前或延迟触发的问题,准确性拉满~
内容的提问来源于stack exchange,提问作者Flick nk
相关产品推荐
相关产品推荐

