2017-02-25 85 views
0

我正在使用Javascript来更改HTML属性,在我的情况下,我有两个相同灯泡开关的照片,我使用2个按钮以“开启”和“关闭”灯泡,但现在我想将这两个按钮替换为第一个图像中开启的同一开关的两个图像,以及第二个图像中开关关闭的图像,如何操作?JavaScript:更改HTML属性

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<h1>What Can JavaScript Do?</h1> 
 

 
<p>JavaScript can change HTML attributes.</p> 
 

 
<p>In this case JavaScript changes the src (source) attribute of an image.</p> 
 

 
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button> 
 

 
<img id="myImage" src="pic_bulboff.gif" style="width:100px"> 
 

 
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button> 
 

 
</body> 
 
</html>
enter image description here

+1

的可能的复制[如何添加/更新使用JavaScript的HTML元素的属性?](http://stackoverflow.com/questions/710275/how-to-add-update-an -attribute-to-html-element-using-javascript) –

回答

0

尝试改变这些

document.getElementById('myImage').src='pic_bulbon.gif' 

到这些

document.getElementById('myImage').setAttribute("src", "pic_bulbon.gif"); 

更多信息:https://www.w3schools.com/jsref/met_element_setattribute.asp

+0

没有人,它不工作 –

+0

@Kujtim Hajdini它必须工作。使用setAttribute函数。 https://jsfiddle.net/rd9d2a2q/1/ –

0

如果我理解你的问题,你希望'打开'按钮是一个开关的图像,而关闭按钮是一个关闭开关的图像。

您可以将background-image属性添加到每个按钮。

<button style="background:url('lightSwitchOn.gif'); background-size: 100px 100px;">Turn on the light</button> 

<button style="background:url('lightSwitchOff.gif'); background-size: 100px 100px;">Turn off the light</button> 

你需要更多的css来调整按钮大小的图像。从CSS中取出CSS并存入一个css文件将有助于保持组织结构。

第二个选择是将灯泡显示为图像并处理它们的'onClick'事件。

1

上面的凯末尔向您展示了解决上述问题的方法,尽管您说这不起作用。那么,证明它实际上必须工作。

<img id="myImage" src="http://placehold.it/150/000/fff" style="width:100px"> 
 

 
<button onclick='document.getElementById("myImage").setAttribute("src", "http://placehold.it/150/E8117F/000")'>PINK</button> 
 
<button onclick='document.getElementById("myImage").setAttribute("src", "http://placehold.it/150/000/fff")'>BLACK</button>