为什么背景颜色在jsfiddle中没有改变

Why does the background color not change in jsfiddle

我从 w3schools 找到了这段代码。它在那里工作但是当我 运行 它在 jsfiddle 中时出现问题。

<input type="text" onfocus="myFunction(this)">


function myFunction(x) {
    x.style.background = "yellow";
}

Here is the code in jsfiddle:

  • 您不需要包含 jquery
  • 将您的脚本添加到 body 而不是 onLoad

See the updated fiddle

已编辑:最好在head

中添加

使用 addEventListener 适合我。

var input = document.getElementsByTagName("input")[0];

input.addEventListener("focus", function() {
    this.style.background = "yellow";
});

http://jsfiddle.net/f11ppv4L/4/