【问题标题】:My background color is not changing with javascript我的背景颜色没有随 javascript 改变
【发布时间】:2018-07-15 21:16:01
【问题描述】:

如果有任何帮助,我将不胜感激,我想我正在编写完全错误的代码。我想在单击按钮时更改标题颜色,使其变为蓝色>单击>红色>单击>绿色。到目前为止,我只能实现蓝色>单击>绿色。它从不经过三种颜色。是否有不同的方式来编写 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>

【问题讨论】:

  • 首先,您的脚本将只运行一次,第二个背景将返回一个 rgb 值,第三个您无法读取带有样式的背景
  • 只定义一个事件监听函数。在 that 中,获取元素背景颜色的当前值,并使用它来确定下一个颜色

标签: javascript jquery html css


【解决方案1】:

你甚至不需要 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>

【讨论】:

  • 欣赏解释。
【解决方案2】:

这是正确的 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>

【讨论】:

  • 请提供信息,不要只粘贴代码:)
  • 想知道投票反对的人的解释吗? OP 是 Javascript 的初学者,我已经更正了 Javascript 代码,因为我也是 Javascript 的新手?编辑(1):谢谢 manniL,从现在开始我会评论和添加符号,我认为代码不正确,感谢您的评论。
  • 现在看起来好多了@GrandIQ!感谢您在这里提出您的解决方案并提供帮助:)
【解决方案3】:

您的代码中的问题是您不断向元素添加越来越多的事件处理程序,而不是只有一个事件处理程序来调整其行为。

由于您已经包含 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 值。

【讨论】:

    【解决方案4】:

    这样的事情怎么样只是有一个颜色数组,然后单击增加索引,并使用 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/

    【讨论】:

      【解决方案5】:

      我也遇到了同样的问题,经过多次搜索,我有了这个解决方案,试试吧...

      // Create our shared stylesheet:
      const sheet = new CSSStyleSheet();
      sheet.replaceSync('#target {color: darkseagreen}');
      
      // Apply the stylesheet to a document:
      document.adoptedStyleSheets = [sheet];
      

      【讨论】:

        猜你喜欢
        • 2013-04-28
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-22
        • 2012-03-20
        • 2017-11-17
        • 2017-03-25
        相关资源
        最近更新 更多