我有一個 Bootstrap 模式,需要在用戶離開頁面時觸發(fā)。在普通 JS 中,解決方案是監(jiān)聽 mouseleave 事件,檢查用戶之前是否手動關(guān)閉了模態(tài)框,如果沒有,則顯示模態(tài)框。document.addEventListener("mouseleave", function (e) { if (e.clientY < 0) { if (localStorage.getItem('newsLetterSignUp') === null) { $('someModal').modal(); } } }, false);我正在嘗試使用 Apline.js 實現(xiàn)相同的行為。第一種方法是在模式本身上設(shè)置事件處理程序:(我有一個自定義模型 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 事件以將其綁定到文檔,但這沒有效果。另一種方法是在 上設(shè)置 @mouseleave 事件,分派事件并在模態(tài)上偵聽事件。但這也沒有導(dǎo)致事件在 mouseleave 上被觸發(fā)。
當(dāng)用戶離開頁面時,如何使用 Aplinejs 觸發(fā)模式?
富國滬深
2023-04-14 15:03:32