如何让滚动事件监听的alert仅触发一次直到页面重载 不设cookie给WP登录用户
你可以在页面脚本的作用域内声明一个内存变量作为触发状态标记,页面刷新时该变量会自动重置,完全不需要依赖cookie就能实现「页面未刷新时仅弹窗1次」的需求。额外还可以在弹窗触发后直接移除滚动事件监听器,减少不必要的性能开销。
具体修改点
- 在
$(document).ready回调的顶层作用域新增状态标记变量,记录弹窗是否已经触发过 - 滚动触发逻辑中增加状态判断,仅当未触发过时执行弹窗逻辑,执行完成后更新状态标记
- 可选优化:弹窗触发后直接移除滚动事件监听器,避免后续滚动时反复执行判断逻辑
修改后的完整JS代码
$(document).ready(function () { // 新增状态标记,记录弹窗是否已经触发,页面刷新时会自动重置为false let modalTriggered = false; const element = document.querySelector('.modalElement'); // 把滚动监听函数单独提出来,方便后续移除 function scrollHandler() { if (is_in_viewport(element)) { trigger_modal(element); } } if (element) { window.addEventListener("scroll", scrollHandler); } /** * Trigger modal * * @param element */ function trigger_modal(element) { // 如果已经触发过,直接中断执行 if (modalTriggered) return; // Check if correct modal_target gets pulled & user is logged in const modal_target = element.getAttribute('data-target'); const user_logged_in = document.body.classList.contains('logged-in'); // If user logged in, show modal unconditionally if (user_logged_in) { //$(modal_target).modal('toggle'); } else { alert('Hello!'); // 标记为已触发 modalTriggered = true; // 移除滚动监听,不需要再执行后续判断 window.removeEventListener('scroll', scrollHandler); // This grabs the correct stored cookie. // let stored_cookie = get_cookie('acceptedPardot' + modal_target + 'Cookie'); // If the cookie doesn't exist, set the cookie and allow for opening the modal /* if (!stored_cookie) { set_cookie('acceptedPardot' + modal_target + 'Cookie', 'true', 30); $(modal_target).modal('toggle'); } */ } } /** * Set cookie * * @param name * @param value * @param days_active * @return {string} */ function set_cookie(name, value, days_active) { let cookie = name + "=" + encodeURIComponent(value); if (typeof days_active === "number") { cookie += "; max-age=" + (days_active * 24 * 60 * 60) + "; path=/"; document.cookie = cookie; } } /** * Get cookie * * @param name * @return {string|null} */ function get_cookie(name) { const cookie_array = document.cookie.split(";"); for (let i = 0; i < cookie_array.length; i++) { const cookie_pair = cookie_array[i].split("="); if (name === cookie_pair[0].trim()) { return decodeURIComponent(cookie_pair[1]); } } return null; } /** * Check if element is in viewport * * @param element * @return {boolean} */ function is_in_viewport(element) { const rect = element.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); } });
内容的提问来源于stack exchange,提问作者user16645285
相关产品推荐
相关产品推荐

