我有这个 jquery 代码:
$(document).ready(function(){
$(".body").hide();
setTimeout(function() {
$(".body").show()
}, 2000);
setTimeout(function() {
$(".img").fadeOut(1000)
}, 1000);
});
而且我希望它仅在首次单击该页面时才起作用。因此,当您重新加载页面或浏览站点并导航回该站点时,上面的脚本将不会执行。
最佳答案
您可以使用 localStorage
在浏览器级别存储值,这样下次用户访问您的网站时,他们将获得相同的数据。如果您在他们访问您的网站时设置一个标志,那么您可以知道他们第一次访问的时间,因为该标志未设置。
这是添加到您的代码中的更改以及相应的注释...
$(document).ready(function(){
// check localStorage to see if we've run this before. If we have then do nothing
if (!localStorage.getItem("first-run")) {
// set a flag in localStorage so we know we've run this before.
localStorage.setItem("first-run", true);
$(".body").hide();
setTimeout(function() {
$(".body").show()
}, 2000);
setTimeout(function() {
$(".img").fadeOut(1000)
}, 1000);
}
});
关于javascript - 我怎样才能做一个只运行一次的javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386282/