1

I put an input button, and set its background with an image, now Ii want to change that image when the button is clicked.

Here is my relevant code:

<div id='back'>
    <input type="button"/>
</div>

CSS code:

#back input{
    width: 130px;
    height: 130px;
    background: url(img/back_default.png);
    border: hidden;
}

Can it be done in CSS (as with links-<a> tags), or should I rely to JavaScript instead? Thanks.

4

3 回答 3

5

不需要Javascript:

#back input {
    width: 130px;
    height: 130px;
    background: url(img/back_default.png);
    border: hidden;
}

#back input:active {
    background-image: url(img/back_default-active.png);
}
于 2012-10-19T03:43:30.220 回答
0

正如马特所说,您可以使用 CSS 的活动伪类来更改背景,或者您可以使用 javascript 将 eventHandler(onClick Listner)添加到更改图像的按钮。

HTML

<div id='back'>
     <input type="button" id="xyz" value="Go to back" class="button"/>
</div>

JS

<script>

el = document.getElementById('xyz');
el.addEvenListener("click",changeImg,false);

function changeImg()
{
    el = document.getElementById('xyz');
    el.style.backround="url('img/back_default-active.png')";
}

</script>
于 2012-10-19T04:04:36.553 回答
0

这应该适用于 JavaScript:

function change() { 
    document.
        getElementById("back").
        getElementsByTagName("input").
        style.backgroundImage = "url(img/anotherImage.png)"
} 

通过单击按钮(或从您想要的任何地方)调用它:

<div id='back'>
    <input type="button" onclick="change()"/>
</div>
于 2012-10-19T03:52:23.107 回答