无法通过javascript更改div中的图像

时间:2016-09-17 17:00:19

标签: javascript html css

这是我的代码:

<!DOCTYPE html>
<html>

<body>
  <script>
    function light() {
      if (document.getElementById("push").value == "OFF") {
        document.getElementById("bulb").style.backgroundImage = url("1.png");
        document.getElementByID("push").value = "ON";
      }
      else {
        document.getElementById("bulb").style.backgroundImage = url("2.png");
        document.getElementByID("push").value = "OFF";
      }
    }
  </script>
  <center>
    <input type="button" id="push" onclick="light()" value="OFF" />
    <div id="bulb" style="background-image:url(2.png);width:320px;height:420px">
    </div>enter code here
  </center>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

这一行:

document.getElementById("bulb").style.backgroundImage = url("1.png");

尝试调用名为url的函数并将字符串传递给它,然后将其结果分配给backgroundImage属性。

相反,您希望直接将字符串分配给backgroundImage

document.getElementById("bulb").style.backgroundImage = "url(1.png)";
// Note ------------------------------------------------^----^----^^

示例:

&#13;
&#13;
document.getElementById("bulb").style.backgroundImage = "url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32)";
&#13;
<div id="bulb" style="width: 32px; height: 32px"></div>
&#13;
&#13;
&#13;

也就是说,最好在CSS中定义样式等,然后使用选择器将这些样式与元素相关联,例如通过类关联:

CSS:

.class-saying-what-the-image-represents {
    background-image: url(1.png);
}

JavaScript的:

document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");

示例:

&#13;
&#13;
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
&#13;
.class-saying-what-the-image-represents {
    background-image: url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32);
}
&#13;
<div id="bulb" style="width: 32px; height: 32px"></div>
&#13;
&#13;
&#13;