代码之家  ›  专栏  ›  技术社区  ›  Paul

当用户离开网站时,生成弹出窗口的最佳方式是什么

  •  0
  • Paul  · 技术社区  · 7 年前

    它工作得很好-至少在桌面上(还没有检查移动设备),除了有一个问题。我只想弹出一次。现在,每当鼠标离开身体时,它就会出现。

    所以,考虑到这一点,我想知道是否有更好的方法来解决这个问题。

    有没有办法把这个限制在工作一次?

    我无法使代码片段正常工作,请在我的测试站点上随意查看。

    $('body').mouseleave(function() {
      $('#specialPop').fadeIn(350);
      $('body').css('overflow', 'hidden');
    });
    $('[data-popup-close]').on('click', function(e) {
      var targeted_popup_class = jQuery(this).attr('data-popup-close');
      $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);
      $('body').css('overflow', 'auto');
      e.preventDefault();
    });
    #specialPop {
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.8);
      color: #FFF;
      position: fixed;
      z-index: 999999;
      margin: 0;
      padding: 0;
      top: 0;
      right: 0;
      bottom: 0;
      display: none;
    }
    
    .popSpecialClose {
      position: absolute;
      right: 40px;
      top: 20px;
      width: 33px;
      height: auto;
      z-index: 99999;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="specialPop" data-popup="popSpecial">
      <a class="popSpecialClose" data-popup-close="popSpecial" href="#">
    		Close
    	</a>
    </div>
    1 回复  |  直到 7 年前
        1
  •  0
  •   Scott Marcus    7 年前

    使用 window.beforeunload ,不是 mouseleave

    $('window').on("beforeunload",function() {
    		$('#specialPop').fadeIn(350);
    		$('body').css('overflow', 'hidden');
    });
    $('[data-popup-close]').on('click', function(e)  {
      var targeted_popup_class = jQuery(this).attr('data-popup-close');
      $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);
      $('body').css('overflow', 'auto');
      e.preventDefault();
    });
    #specialPop {
    	width: 100%;
    	height: 100%;
    	background: rgba(0,0,0,0.8);
    	color: #FFF;
    	position: fixed;
    	z-index: 999999;
    	margin: 0;
    	padding: 0;
    	top: 0;
    	right: 0;
    	bottom: 0;
    	display: none;
    }
    .popSpecialClose {
    	position: absolute;
    	right: 40px;
    	top: 20px;
    	width: 33px;
    	height: auto;
    	z-index: 99999;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="specialPop" data-popup="popSpecial">
    	<a class="popSpecialClose" data-popup-close="popSpecial" href="#">
    		Close
    	</a>
    </div>
    推荐文章