Javascript 当用户离开页面导航时,如何使用Aplinejs触发模态?

Javascript 当用户离开页面导航时,如何使用Aplinejs触发模态?,javascript,bootstrap-4,alpine.js,Javascript,Bootstrap 4,Alpine.js,我有一个引导模式,当用户离开页面时需要触发它。在纯JS中,解决方案是监听mouseleave事件,检查用户之前是否手动关闭了模式,如果没有,则显示模式 document.addEventListener("mouseleave", function (e) { if (e.clientY < 0) { if (localStorage.getItem('newsLetterSignUp') === null) {

我有一个引导模式,当用户离开页面时需要触发它。在纯JS中,解决方案是监听mouseleave事件,检查用户之前是否手动关闭了模式,如果没有,则显示模式

document.addEventListener("mouseleave", function (e) {
        if (e.clientY < 0) {
          if (localStorage.getItem('newsLetterSignUp') === null) {
            $('someModal').modal();
          }
        }
      }, false);
document.addEventListener(“mouseleave”,函数(e){
如果(e.clientY<0){
if(localStorage.getItem('newslettesignup')==null){
$('someModal').modal();
}
}
},假);
我正试图通过Apline.js实现同样的行为

第一种方法是在模式本身上设置事件处理程序: (我有一个自定义模型CSS类.newsletter modal而不是Bootstrap的.modal,因为我想用Alpine处理可见性)


[模态内容]
window.newsletter=函数(){
返回{
是的,
revealModal(e){
警惕(“离开”);
if(e.clientY<0&&localStorage.getItem('newslettesignup')==null){
this.showModal=true;
}
},
关闭模式(){
this.showModal=false;
localStorage.setItem('newslettesignup',JSON.stringify(newdate());
}
}
}
我的想法是将.document属性添加到@mouseleave事件,以便将其绑定到文档,但这没有效果


另一种方法是在上设置@mouseleave事件,分派事件并在模式上侦听事件。但这也没有导致在mouseleave上触发事件。

事实证明,问题不在事件处理程序或Alpine中,而在Firefox中。在Firefox中,当用户导航鼠标离开窗口时,不会触发mouseleave事件。这种行为在本文中得到了解释

因此Firefox的解决方案是添加一个额外的事件监听器来跟踪鼠标移动。并在e.clientY<10时立即触发

// HTML
<div x-data="newsletter()" @mouseleave.window="revealModal" @mousemove.document="isUserLeaving"> ... </div>
// JS
isUserLeaving(e) {
   if (e.clientY < 10) {
       this.revealModal();
   }
}
//HTML
... 
//JS
伊斯兰堡(e){
如果(e.clientY<10){
这个。revealModal();
}
}

我发现使用mouseout事件确实会触发事件,但mouseout的问题是它也会在绑定到的元素的子元素上触发。
// HTML
<div x-data="newsletter()" @mouseleave.window="revealModal" @mousemove.document="isUserLeaving"> ... </div>
// JS
isUserLeaving(e) {
   if (e.clientY < 10) {
       this.revealModal();
   }
}