简体   繁体   English

JavaScript:更改HTML属性

[英]JavaScript: change HTML attributes

I'm using Javascript to change HTML attributes,in my case I have 2 photos of the same light bulb that is switched on/off and I'm using 2 buttons in order to "switch on" and "switch off" the light bulb,but now I want to displace these 2 buttons into 2 images of the same switch that is on in the first pic and the second pic that the switch is off,how to do it? 我使用Javascript更改HTML属性,在我的情况下,我有2张打开/关闭同一灯泡的照片,并且使用2个按钮来“打开”和“关闭”灯泡,但是现在我想将这2个按钮替换为第一张图片中的同一开关的第二张图片和第二张图片中该开关已关闭的图片,该怎么做?

 <!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 在此处输入图片说明

Kemal above demonstrated you way to solve your problem above, although you said it didn't work. 以上的凯末尔(Kemal)展示了您解决上述问题的方法,尽管您说这没有用。 Well, here's prove it actually has to be working. 好吧,这证明它实际上必须起作用。

 <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> 

Try changing these 尝试更改这些

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

into those 到那些

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

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

If I understand your question you want the 'turn on' button to be an image of an on switch, and the turn off button to be an image of an off switch. 如果我理解您的问题,您希望“打开”按钮是打开开关的图像,而“关闭”按钮是打开开关的图像。

You could add a background-image property to each button. 您可以将背景图像属性添加到每个按钮。

<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>

You would need more css to resize the button to the size of the image. 您需要更多的CSS才能将按钮的大小调整为图像的大小。 Taking the css out of the html and into a css file will help keep things organised. 将css移出html并放入css文件将有助于保持事物的井井有条。

A second option would be to display the light bulbs as images and handle their ' onClick ' event. 第二种选择是将灯泡显示为图像并处理其“ onClick ”事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM