窗口,滚动脚本不会触发/触发?

时间:2021-04-09 12:50:18

标签: javascript html jquery

我有这个脚本:

<script type="text / javascript">
/* Popup on scroll. */
jQuery(function($){
$(window).one('scroll',function() {
  var y = $(this).scrollTop();
  if (y > 100) {
    $('.popup').css({display: 'flex'}).fadeIn();
    document.getElementById('content').style.display = "none";
  } else {
    $('.popup').css({display: 'none'}).fadeOut();
  }
});
});

jQuery(function($){
$('.popup-link').on('click', function(){
    $(this).closest(".popup").remove();
    document.getElementById('content').style.display = "block";
});
});
</script>   

在 HTML 中的使用:

<div class="popup">
    <div class="popup-page">
        <a class="popup-link" href="url" target="_blank">
This is LINK TEXT.
        </a>
    </div>
</div>

出于某种原因,如果页面重新加载一半,它就可以工作,但不,它根本不会触发,而且在它工作之前,我不知道发生了什么。 我在 wordpress 网站上使用这个。

1 个答案:

答案 0 :(得分:0)

使用 jQuery's .on() 代替 .one()
之后要删除任何侦听器,请使用 .off() method:

jQuery(function($) {

  // POPUP
  // Yep, all you need for all your popups
  $("[data-popup]").on("click", function() {
    $(this.dataset.popup).toggleClass("show");
  });

  // CUSTOM POPUP STUFF
  const $popupCustom = $("#popup-custom");

  function popupScroll() {
    $popupCustom.toggleClass("show", $(window).scrollTop() > 100);
  }
  
  function popupDestroy() {
    // Remove listener from window scroll using .off()
    $(window).off('scroll', popupScroll);
  }

  // Listen for window scroll:
  $(window).on('scroll', popupScroll);
  
  // Destroy the scroll listener on click:
  $("#popup-destroy").on("click", popupDestroy);

});
body {
  min-height: 300vh; /* DEMO ONLY */
}

.popup {
  position: fixed;
  z-index: 10000;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px);
  transition: 0.3s;
  pointer-events: none;
  opacity: 0;
  visibility: hidden;
}

.popup.show {
  pointer-events: auto;
  opacity: 1;
  visibility: visible;
}

.popup-page {
  padding: 20px;
  background: #fff;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}
<div id="popup-custom" class="popup">
  <div class="popup-page">
    <h1>Hello, World</h1>
    <button type="button" data-popup="#popup-custom" id="popup-destroy">DON'T SHOW ON SCROLL AGAIN!</button>
  </div>
</div>

<div id="content">
  <h1>THIS IS SOME CONTENT</h1>
  Scroll or<br>
  <button type="button" data-popup="#popup-custom">SHOW POPUP</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>