使用 html 会话存储隐藏运行一次的 div



我的网站中有这个div 的 id,id是 se-pre-con,我只想在每次网站访问时显示一次。我想使用会话存储在运行一次后不显示 se-pre-con 的 htmldiv。但可以做一些关于如何处理这个问题的建议。

 <div class="se-pre-con"></div> // the relevant html
.no-js #loader { display: none;  } // the relevant css
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(Preloader_10.gif) center no-repeat #fff;
}
 <script> // the relevant jquery
// Wait for window load
$(window).load(function() {
    // Animate loader off screen
    $(".se-pre-con").fadeOut("slow");;
});

</script>

目前还不清楚你想从哪里调用该代码,但如果我是你,我会稍微反转一下代码。也就是说,始终在load事件上执行您的东西,并决定在其中做什么。此时,将要淡出的对象加载放在函数中并从其他地方调用该代码段变得微不足道(并且您没有指定要从何处调用它,所以我必须猜测您想在sessionStorage中设置值后调用它。

function fadeObject() {
    $(".se-pre-con").fadeOut("slow");
}
$(window).load(function() {
    if (sessionStorage.getItem('htmldivwithid') !== 'false') {
        fadeObject();
    } else {
        document.getElementById('htmldivwithid').style.display="none";
        sessionStorage.setItem('htmldivwithid','true');
        // call fadeObject()?
    }
});

此时,您可以在需要时从load事件内部调用fadeObject()(我在我希望您可能想要调用它的地方放置了一条评论(。

fadeObject不是绝对必要的,但是如果您需要更改淡入淡出的对象,一旦您决定要调用它的位置,您现在只有一个地方可以更改,而不是两个。

我通过在 html 页面的正文部分使用此脚本来回答我自己的问题,它确保加载器在每个浏览器会话中只运行一次,正如我试图实现的那样。

<script>
if (sessionStorage.getItem('se-pre-con') !== 'true'){
// if the storage item 'se-pre-con', does not exist, run the code in curly 
braces
document.getElementById("se-pre-con").style.display = 'block';}
else {
document.getElementById('se-pre-con').style.display="none";
// else (when above if statement is not met) hide the loader
}

sessionStorage.setItem('se-pre-con','true');
</script>

最新更新