弹出框以在每次站点访问时出现一次

时间:2015-12-09 05:17:49

标签: javascript jquery

我的网站上出现了一个弹出框,每次访问或刷新主页时都会出现该弹出框。我设法使用......

var firstTime = localStorage.getItem("firstTime");
if(! firstTime){

localStorage.setItem("firstTime", true);
}
});

...让它只出现一次,但是有人知道每次访问网站(而不是页面)时我是如何出现的吗?这样,当你回到网站时,它就不会出现。任何帮助都会很棒!完整代码如下......

    <script type="text/javascript">
    $(document).ready(function() {  
    var firstTime = localStorage.getItem("firstTime");

    if(! firstTime){

        var id = '#dialog';

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        //transition effect     
        $('#mask').fadeIn(500); 
        $('#mask').fadeTo("slow",0.9);  

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);

        //transition effect
        $(id).fadeIn(500);  

    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });     

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });     
           localStorage.setItem("firstTime", true);
    }
    });

</script>

//rest of html content

    <!-- Pop-up window - Subscribe -->
<div id="boxes">
<div style="top: 199.5px; left: 551.5px; display: none;" id="dialog" class="window">
<a href="#" class="close">X</a>
<center><img src="img/pop-up-logo.png" alt=""/><br><br><br>

<a href="subscribe.html" class="btn btn-primary"><strong>Subscribe</strong> </a> <br><br>

    <h2>to receive email updates</h2> </center>
</div>
<!-- Mask to cover the whole screen -->
<div style="width: 1478px; height: 602px; display: none; opacity: 0.8;" id="mask"></div>
</div>
<!-- Pop-up window - Subscribe End -->

1 个答案:

答案 0 :(得分:1)

您必须检查上次访问页面的时间,通常30分钟的会话很常见(虽然没有足够的数据来支持这一点)

所以,设置访问而不是在本地存储中的时间

localStorage.setItem("visitTime", new Date().getTime() );

并在下次检查此值,无论是在30分钟之前(或安全的60分钟)还是30分钟(或60分钟)之后

为您更新了此fiddle。截至目前,我已将间隔时间设置为1分钟,以便您可以对其进行测试。

var timeIntervalToAssumeNewSiteVisit = 1*60*1000; //in milliseconds
$(document).ready(function() {  

  var currentTime = new Date().getTime();
    var lastVisitTime = parseInt( localStorage.getItem("lastVisitTime") );

    if( isNaN( lastVisitTime ) || ( currentTime - lastVisitTime )  >= timeIntervalToAssumeNewSiteVisit )
      {
        alert( "new visit" );
      }
  else
    {
      alert( "same visit, old session" );
    }
       localStorage.setItem("lastVisitTime", currentTime);

});