简单,如果还有onclick然后呢?

Mar*_*yon 5 html javascript css if-statement onclick

  1. 如果点击是按钮改变颜色,我该怎么做呢?
  2. 使用.onclick是最好的选择吗?
  3. 我这样做是最好的方式吗?

谢谢.

HTML:

<body>
<div id="box"></div>
<button id="yes">yes</button>
<button id="no">no</button>
<script src="js/script.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)

CSS:

#box {
    width: 200px;
    height: 200px;
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

JS:

function Choice () {
    var box = document.getElementById("box");
    var yes = document.getElementById("yes");
    var no = document.getElementById("no");

    if (yes.clicked == true) {
        box.style.backgroundColor = "red";
    } else if (no.clicked == true) {
        box.style.backgroundColor = "green";
    } else {
        box.style.backgroundColor = "purple";
    };
};

Choice ();
Run Code Online (Sandbox Code Playgroud)

Mar*_*xtn 6

您应该使用onclick方法,因为该函数在加载页面时运行一次,然后不会单击任何按钮

因此,每当用户按任意键将更改添加到div背景时,您必须添加偶数运行

所以函数应该是这样的

htmlelement.onclick() = function(){
    //Do the changes 
}
Run Code Online (Sandbox Code Playgroud)

所以你的代码必须看起来像这样:

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");

yes.onclick = function(){
    box.style.backgroundColor = "red";
}

no.onclick = function(){
    box.style.backgroundColor = "green";
}
Run Code Online (Sandbox Code Playgroud)

这意味着当单击#yes按钮时,div的颜色为红色,单击#no按钮时背景为绿色

这是一个Jsfiddle


Xot*_*750 6

首选的现代方法是addEventListener通过将事件侦听器直接添加到元素或元素的父元素(委托)来使用。

使用委托事件的一个示例可能是

var box = document.getElementById('box');

document.getElementById('buttons').addEventListener('click', function(evt) {
  var target = evt.target;
  if (target.id === 'yes') {
    box.style.backgroundColor = 'red';
  } else if (target.id === 'no') {
    box.style.backgroundColor = 'green';
  } else {
    box.style.backgroundColor = 'purple';
  }
}, false);
Run Code Online (Sandbox Code Playgroud)
#box {
  width: 200px;
  height: 200px;
  background-color: red;
}
#buttons {
  margin-top: 50px;
}
Run Code Online (Sandbox Code Playgroud)
<div id='box'></div>
<div id='buttons'>
  <button id='yes'>yes</button>
  <button id='no'>no</button>
  <p>Click one of the buttons above.</p>
</div>
Run Code Online (Sandbox Code Playgroud)