繁体   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