首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的背景色不会随javascript而改变

我的背景色不会随javascript而改变
EN

Stack Overflow用户
提问于 2018-07-16 05:16:01
回答 5查看 3.3K关注 0票数 0

我非常感谢任何人的帮助,我想我写这段代码是完全错误的。我想改变我的标题颜色点击按钮,使它变成蓝色>click>红色>点击>绿色。到目前为止,我只能实现蓝色>click>绿色。它从来不会有三种颜色。有没有不同的方式来编写if语句?或者是另一种我不知道的方法,可以让我有一些有条件的css样式改变?

代码语言:javascript
复制
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";

    });

} 
代码语言:javascript
复制
* {
    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;
}
代码语言:javascript
复制
<!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>

EN

回答 5

Stack Overflow用户

发布于 2018-07-16 05:28:21

这是正确的Javascript:

当我们监听myBtn被点击时,我们只需要一个实例,所以我移动了所有的实例并将它们移动到一个实例中。我还在Javascript中声明了颜色,这样您只需单击按钮一次即可激活颜色。

manniL在这篇文章中给出了更高级的答案!

代码语言:javascript
复制
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";

} 

});
代码语言:javascript
复制
* {
    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;
}
代码语言:javascript
复制
<!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>

票数 2
EN

Stack Overflow用户

发布于 2018-07-16 05:33:29

您甚至不需要为此使用jquery。所以使用纯javascript吧。我还建议使用ES6 (基于varconstlet以及更多...)。

不是在事件处理程序声明周围添加if语句,而是将它们放在其中(请参阅const color)。

还要注意,background样式具有比颜色更多的值(例如,重复)。您可以只设置和检查backgroundColor,也可以按空格拆分background值并获取第一个条目(这是实际的颜色集)。

代码语言:javascript
复制
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
}
代码语言:javascript
复制
<!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
EN

Stack Overflow用户

发布于 2018-07-16 05:55:14

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

既然您已经包含了jquery,我希望您能接受使用它的答案。你可以用这段代码替换main.js,它应该会给出你想要的结果。

代码语言:javascript
复制
$(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值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51352291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档