簡體   English   中英

我的背景顏色沒有使用javascript更改

[英]My background color is not changing with javascript

我將不勝感激,我想我將完全錯誤地編寫此代碼。 我想在單擊按鈕時更改標題顏色,使其變為藍色>單擊>紅色>單擊>綠色。 到目前為止,我只能實現BLUE> click> GREEN。 它永遠不會經歷三種顏色。 是否有其他方式編寫if語句? 還是我不知道的其他方法會讓我有條件地更改CSS樣式?

 var mySwitch = document.getElementById('header').style.background; if (mySwitch == "darkblue") { document.getElementById("myBtn").addEventListener("click", function(){ document.getElementById("header").style.background = "red"; }); } else if (mySwitch == "red") { document.getElementById("myBtn").addEventListener("click", function(){ document.getElementById("header").style.background = "green"; }); } else { document.getElementById("myBtn").addEventListener("click", function(){ document.getElementById("header").style.background = "darkblue"; }); } 
 * { margin: 0; padding: 0; list-style: none; font-family: sans-serif; } #header { background: darkblue; color: white; display: flex; justify-content: space-around; height: 12vh; } #header h1 { text-align: left; margin-top: 30px; } .main-nav ul { padding: 0px; font-size: 1.5rem; display: flex; margin-top: 40px; } .main-nav a { color: white; padding: 20px; text-decoration: none; } .main-nav a:hover { color: rgb(255, 148, 148); } .hero-section { background-image: url("https://stackoverflow.blog/wp-content/uploads/2018/01/BrutalLifeCycleJavascript.png"); background-position: center; background-size: cover; background-repeat: no-repeat; height: 80vh; color: white; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; } button { background: black; height: 40px; width: 80px; color: white; margin-top: 20px; animation: jumpbutton 1s ease-out infinite; outline: none; border-radius: 15px; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="style.css" type="text/css"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> </head> <body> <header id="header"> <nav class="main-nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header> <div class="hero-section"> <h1>JAVASCRIPT</h1> <p id="paragraph">This is a testing environment</p> <button type="submit" id="myBtn"> CLICK ME </button> </div> <div class="about-box"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, asperiores!</p> </div> <!-- CHANGE HEADER COLOR, BACKGROUND & HERO IMAGE--> <!--- --> <script src="main.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> 

這是正確的Javascript:

當我們收聽被單擊的myBtn時,我們只需要一個實例,因此我移動了所有實例並將它們移動到一個實例中。 我還在Javascript中聲明了顏色,因此您只需單擊一次按鈕即可激活顏色。

manniL在本文中給出了更高級的答案!

 document.getElementById('header').style.background = "darkblue"; // Declare the initial background color here, so that you don't have to press "Click Me" twice to get it to work! document.getElementById("myBtn").addEventListener("click", function(){ var mySwitch = document.getElementById('header').style.background; if (mySwitch == "darkblue") { document.getElementById("header").style.background = "red"; } else if (mySwitch == "red") { document.getElementById("header").style.background = "green"; } else { document.getElementById("header").style.background = "darkblue"; } }); 
 * { margin: 0; padding: 0; list-style: none; font-family: sans-serif; } #header { background: darkblue; color: white; display: flex; justify-content: space-around; height: 12vh; } #header h1 { text-align: left; margin-top: 30px; } .main-nav ul { padding: 0px; font-size: 1.5rem; display: flex; margin-top: 40px; } .main-nav a { color: white; padding: 20px; text-decoration: none; } .main-nav a:hover { color: rgb(255, 148, 148); } .hero-section { background-image: url("https://stackoverflow.blog/wp-content/uploads/2018/01/BrutalLifeCycleJavascript.png"); background-position: center; background-size: cover; background-repeat: no-repeat; height: 80vh; color: white; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; } button { background: black; height: 40px; width: 80px; color: white; margin-top: 20px; animation: jumpbutton 1s ease-out infinite; outline: none; border-radius: 15px; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="style.css" type="text/css"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> </head> <body> <header id="header"> <nav class="main-nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header> <div class="hero-section"> <h1>JAVASCRIPT</h1> <p id="paragraph">This is a testing environment</p> <button type="submit" id="myBtn"> CLICK ME </button> </div> <div class="about-box"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, asperiores!</p> </div> <!-- CHANGE HEADER COLOR, BACKGROUND & HERO IMAGE--> <!--- --> <script src="main.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> 

您甚至不需要jquery。 因此,請使用純JavaScript。 我還建議使用ES6( constlet var等等)。

與其在事件處理程序聲明周圍添加if語句,不如在事件處理程序聲明中添加它們(請參閱const color )。

還應注意, background樣式的值不僅僅是顏色(例如重復)。 您可以只設置和檢查backgroundColor ,也可以按空間分割background值並獲取第一個條目(這是實際的顏色集)。

 const header = document.getElementById('header') document.getElementById("myBtn").addEventListener("click", () => { const headerBg = header.style.background.split(" ")[0] const color = headerBg == "red" ? "green" : headerBg == "darkblue" ? "red" : "darkblue" changeBg(header, color) }) const changeBg = (n, color) => { n.style.background = color } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <header id="header"> <nav class="main-nav"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header> <div class="hero-section"> <h1>JAVASCRIPT</h1> <p id="paragraph">This is a testing environment</p> <button type="submit" id="myBtn"> CLICK ME </button> </div> <div class="about-box"> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, asperiores!</p> </div> </body> </html> 

代碼中的問題是,您一直在向元素添加越來越多的事件處理程序,而不是使用一個事件處理程序來調整其行為。

由於您已經包含了jquery,所以我希望您會接受使用它的答案。 您可以使用此代碼替換main.js,它應該會為您提供所需的結果。

$(document).on('click', '#myBtn', function() {
    let color;
    switch (document.getElementById('header').style.background) {
        case 'darkblue':
            color = 'red';
            break;
        case 'red':
            color = 'green';
            break;
        default:
            color = 'darkblue';
            break;
    }
    $('#header').css('background', color);
});

jQuery文檔單擊處理程序是我發現自己經常使用的一種模式。 它綁定到文檔,因此您不必擔心在創建元素后運行代碼。 如果該元素存在,即使在某個時候將其刪除,單擊該處理程序也會觸發該處理程序。

您會注意到document.getElementById('header').style.background仍然是常規javascript-這是因為使用$('#header').css('background')會為您提供一個計算得出的RGB值,該值不會匹配顏色名稱字符串。

像這樣的事情如何呢?只是擁有一系列顏色,然后單擊增加索引,並使用mod運算符獲取正確的索引。

  $(document).ready(function() {
  let i = 0;
  let colors = ['red', 'green', 'blue','purple', 'orange', 'pink'];
  $('button').click(function() {
    $('.header').css("background-color", colors[i++ % colors.length]);
  })
});

https://jsfiddle.net/s0L4mgea/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM