2017-07-27 73 views
0

美好的一天每个人我都有一个工作我的加载只有一次麻烦。因为当我刷新页面或如果我要去另一个页面它总是加载。 这里是到目前为止我的代码:加载需要只工作一次

JS

<!--Auto load the on overlay function--> 
<script> 
    window.onload = function openNav() { 
    document.getElementById("myNav").style.width = "100%"; 
    splashScreen(); 
} 

function closeNav() { 
    document.getElementById("myNav").style.width = "0%"; 
} 
</script> 

,这里是我的js功能为我splashscreen.js

//use onload when in your html the context is not inside 
//the <header> 
//create a splashScreen function 
function splashScreen(){ 
//get the element on the html side with the id of "skip" 
var skipButton = document.getElementById("skip"); 
//counter for the countdown 
var counter = 5; 
//create an element <p> 
var newElement = document.createElement("p"); 
newElement.innerHTML = "Skip this 5 seconds"; 
var id; 

skipButton.parentNode.replaceChild(newElement, skipButton); 

id = setInterval(function(){ 
counter--; 
    if(counter < 0){ 
     //replace the newElement on else condition statement 
     newElement.parentNode.replaceChild(skipButton, newElement); 
     clearInterval(id); 
    } else { 
     newElement.innerHTML = "You can skip this in " + counter.toString() + " seconds."; 
    } 
}, 1000); 
} 

,这是我怎么称呼它在我的html

<html> 
    <body> 
<!--SplashScreen JS--> 
<script src="<?php echo base_url('assets/public/js/splashscreen.js');?>"> 
</script> 

回答

0

一种方法是设置window.name财产,这仍然window后进行设置。

const NAME = "once"; 

window.onload = function openNav() { 
    document.getElementById("myNav").style.width = "100%"; 
    if (this.name !== NAME) { 
     this.name = NAME; 
     splashScreen(); 
    } else { 
     // do other stuff 
     console.log(this.name) 
    } 
} 
+0

我这样做了'''const NAME =“once”; window.onload = function openNav(){ document.getElementById(“myNav”)。style.width =“100%”;如果(this.NAME!== NAME){ splashScreen(); } else { alert(this.name); }我的导航栏上有''' –

+0

我有画廊,当我去我们团队时,我们的团队仍然弹出 –

+0

'this.NAME'与'window'的'name'属性不一样。查看更新后的帖子 – guest271314

1

刷新页面或转到其他页面时,返回到原始页面,页面正在重新加载,因此将调用onLoad处理程序。

如果你想要某些功能只发生一次,那么你可以尝试的一件事是设置一个cookie,你可以检查页面加载。如果设置了cookie,则知道您已经加载了一次,并且不要再次运行代码。如果没有,则运行代码,然后设置cookie。

有用的链接,饼干: https://www.w3schools.com/js/js_cookies.asp

+1

或者使用localStorage的 –

+0

@ScottMarcus先生,我如何能实现它 –

+0

@PaulKevinMacandili这是一个很好的教程:https://www.smashingmagazine.com/2010/10/local-storage- (或者你可以在下面看到Scott的答案,这可能与问题更相关) –

0

为了能够知道,闪屏已经显示给定用户,你需要的东西存储到该页面加载事件之间仍然存在这种效果。由于页面将在点击刷新按钮时重新加载,或者在之前返回到页面时重新加载,因此该存储的项目不能位于页面本身中,因为每次加载页面时都会重新初始化。

饼干(如另一个答案中提到)是一个选项,但localStorage,我觉得更简单。它的工作原理是这样的:

// Once the window is loaded... 
window.addEventListener("load", function(){ 

    // Check localStorage to see if the splash screen 
    // has NOT already been displayed 
    if(!localStorage.getItem("splash")){ 

    // Splash has not been displayed, so show it: 
    splashScreen(); 

    // Store a value in localStorage to denote that the splash screen 
    // has now been displayed 
    localStorage.setItem("splash", "true"); 
    } 
});