2017-07-27 72 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"); 
    } 
});