这是一个没有 jQuery 的解决方案,应该适用于桌面浏览器上的 IE8+,当用户将鼠标指向页面顶部时会触发:
document.addEventListener('mouseleave', function(e) {
// position of the mouse when it leaves the document, we only care about the top of the document so we use `e.pageY`
console.log('e.pageY: ', e.pageY);
// get the position of where the page is scrolled to.
console.log('document.body.scrollTop: ', document.body.scrollTop);
console.log(e.pageY - document.body.scrollTop);
var isLeaving = e.pageY - document.body.scrollTop;
// you can adjust this number value to compensate if the user leaves
if (isLeaving <= 50) {
// do something here!
}
});
此代码段的一般目的是检测用户退出页面的意图,然后执行诸如触发模式之类的操作。
document.addEventListener('mouseleave', e => {
var isLeaving = e.pageY - document.body.scrollTop;
if (isLeaving <= 50) {
// do something ...
let elms = document.querySelectorAll('.target');
for (var i = elms.length - 1; i >= 0; i--) {
elms[i].innerHTML = 'Welcome Back!'
}
}
});
html, body, section {
min-height: 100vh;
min-width: 100vw;
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
}
h1 {
text-align: center;
}
<section>
<h1 class="target">Get ahead and try to leave</h1>
</section>
<section>
<h1 class="target">Get ahead and try to leave</h1>
</section>
<section>
<h1 class="target">Get ahead and try to leave</h1>
</section>
<section>
<h1 class="target">Get ahead and try to leave</h1>
</section>