我有一個 Bootstrap 模式,需要在用戶離開頁面時觸發。在普通 JS 中,解決方案是監聽 mouseleave 事件,檢查用戶之前是否手動關閉了模態框,如果沒有,則顯示模態框。document.addEventListener("mouseleave", function (e) { if (e.clientY < 0) { if (localStorage.getItem('newsLetterSignUp') === null) { $('someModal').modal(); } } }, false);我正在嘗試使用 Apline.js 實現相同的行為。第一種方法是在模式本身上設置事件處理程序:(我有一個自定義模型 CSS 類 .newsletter-modal 而不是 Bootstrap 的 .modal 因為我想用 Alpine 處理可見性)<div x-data="newsletter()"> <div x-show="showModal" @mouseleave.document="revealModal" class="newsletter-modal show fade" id="mailingListModal" tabindex="-1" role="dialog" aria-labelledby="mailingListModal" aria-hidden="true" > <div class="modal-dialog modal-lg" role="document"> <div class="modal-content" @click.away="showModal = false"> [modal content] </div> </div> </div> <--- JS code to handle the modal actions ---> <script> window.newsletter = function() { return { showModal: true, revealModal(e) { alert('leave'); if (e.clientY < 0 && localStorage.getItem('newsLetterSignUp') === null) { this.showModal = true; } }, closeNewsletterModal() { this.showModal = false; localStorage.setItem('newsLetterSignUp', JSON.stringify(new Date())); } } } </script> 我的想法是將 .document 屬性添加到 @mouseleave 事件以將其綁定到文檔,但這沒有效果。另一種方法是在 上設置 @mouseleave 事件,分派事件并在模態上偵聽事件。但這也沒有導致事件在 mouseleave 上被觸發。
當用戶離開頁面時,如何使用 Aplinejs 觸發模式?
富國滬深
2023-04-14 15:03:32