JS用按钮改变图像

时间:2013-11-24 05:49:31

标签: javascript html css styles

JS

var identbutton = document.getElementById('imagebutton');
var imag = document.getElementById('contentimage');
var runtext = function(){
    imag.style.background="url(../images/contimgtwo.jpg)";
}
identbutton.addEventListener("click",runtext,"false");

HTML

    <button id="imagebutton">click here to change images</button>
<img id="contentimage"></a>

CSS

#contentimage { 
display:block; 
background:url(../images/contimg.jpg);
top:1600px;
width:500px; 
height:400px; 
position:absolute;
} 

#contentimage:hover { 
    opacity:0.5; 
    cursor:crosshair;
}

当我按下按钮时,我正在尝试更改图像,因此当您按下按钮时,图像的样式将被假设为更改图像。这有效,你可以看到图像变化,除了你看到的是图像轮廓周围的薄黑色边框和中间的白色空间,所以你看不到图像。还尝试了.className方法而不是.style并且无法正常工作

1 个答案:

答案 0 :(得分:1)

您应该使用img标签的src属性而不是background属性来设置图像。如果要使用background属性,请使用div标签而不是img标签。以下是使用src属性的示例..

http://jsfiddle.net/2tSbq/

基本上,它和你正在做的一样,除了我直接在html中设置图像的初始值...

<img src="https://www.somewebsite.com/someimage.jpg" id="contentimage">

然后使用javascript更新它...

imag.src = 'http://www.somewesbtie.com/anotherimage.jpg";
相关问题