简体   繁体   中英

change the image background of a button when it's clicked

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.

Javascript is not needed:

#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);
}

This should work with JavaScript:

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

Call it from your button click (or from anywhere you want):

<div id='back'>
    <input type="button" onclick="change()"/>
</div>

It's as Matt Said you could use CSS's active pseudo class to change the background or alternatively you could use javascript to add an eventHandler (onClick Listner )to the button that changes the image.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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