2016-07-05 81 views
0

請注意,我沒有使用類。我沒有找到這個具體問題的答案。如何使用javascript編程按鈕以更改樣式表

使用JavaScript,我怎樣才能編程一個按鈕來更改每次單擊按鈕時的樣式表?

我已經嘗試了不同的if,else if和else,但是當我嘗試它們時,它打破了代碼(即它會將顏色更改爲藍色,如果是紅色,但不會再回來)。
它與2個按鈕一起工作,但每次單擊一個按鈕時都會更改該按鈕,似乎無法使用該按鈕。我得到了餵養並編程了第二個按鈕,將它改回來。

這適用於2個按鈕:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>"Your Title Here"</title> 
    <link id="um" rel="stylesheet" href="stylesheet1.css"> 
     <style> 
     </style> 

</head> 

<body> 
<p>booga</p> 
<button id="x" onclick="myFunction()">blue</button> 
<button id="x1" onclick="myFunction1()">red</button> 

<script> 
function myFunction() { 
if (document.getElementById("um").href = "stylesheet1.css"){ 
document.getElementById("um").href = "stylesheet2.css"} 
} 
function myFunction1() { 
if (document.getElementById("um").href = "stylesheet2.css"){ 
document.getElementById("um").href = "stylesheet1.css"} 
} 
</script> 
</body> 

我希望能夠擺脫第二個按鈕和第二功能,並擁有這一切與一個按鈕。

編輯... 我試過了,失敗了。

function myFunction() { 
if (document.getElementById("um").href == "stylesheet1.css") 
{document.getElementById("um").href = "stylesheet2.css"}; 
else {document.getElementById("um").href = "stylesheet1.css"} 
} 
+0

@Typo:嗯,沒有它不行。 – Ryan

+0

當有人總是說「哦,這是重複的!和你在一起!」時,一個新的程序員如何得到這個網站上的任何代表? – Bugiroff

+0

@Bugiroff耐心點,事情需要時間。你有什麼辦法我的投票 –

回答

2

確保您使用==而不是=來進行比較!

if (document.getElementById("um").href == "stylesheet1.css") 

+0

並不能解決整個問題... href屬性將是絕對url,不屬於同一屬性值 – charlietfl

+0

所以更多沿線:\t function myFunction(){ \t if(document.getElementById (「um」)。href ==「stylesheet1.css」) \t {document.getElementById(「um」)。href =「stylesheet2.css」}; \t else {document.getElementById(「um」)。href =「stylesheet1.css」} \t} – Bugiroff

+1

要檢查樣式表名稱,您應該可以使用if(document.getElementById(「um」)。 href.indexOf(「stylesheet1」)> -1) – will

0

試試這個:

<button id="x" onclick="myFunction()">Change</button> 

<script> 

    function myFunction() { 
     var link = document.getElementById("um"); 
     var segments = link.href.split('/'); 
     var currentStyle = segments[segments.length - 1]; 
     var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2' 
                 : 'stylesheet1'; 
     document.getElementById("um").href = style + ".css" 
    } 

</script> 
+0

在我的情況console.log(document.getElementById(「um」)。href)返回file:/// C:/ Users/aespiritu/Desktop/aloha/stylesheet1。 CSS –

0
<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>"Your Title Here"</title> 
    <link id="um" rel="stylesheet" href="stylesheet1.css"> 

</head> 

<body> 
<p>booga</p> 
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button> 

<script> 
function myFunction(id,a,b) { 
    var el = document.getElementById(id); 
    var hrefStr; 
    if(~el.href.indexOf(a)) { 
     hrefStr = el.href.replace(a, b); 
     el.href = hrefStr; 
    } else { 
     hrefStr = el.href.replace(b, a); 
     el.href = hrefStr; 
    } 
} 
</script> 
</body> 
</html> 
相關問題