admin管理员组

文章数量:1391975

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.

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.

Share Improve this question edited Oct 19, 2012 at 3:53 Derek 朕會功夫 94.5k45 gold badges198 silver badges253 bronze badges asked Oct 19, 2012 at 3:38 MallocMalloc 16.3k35 gold badges108 silver badges196 bronze badges 3
  • Do you want the background to change only during the click or from then on? – Phil Commented Oct 19, 2012 at 3:45
  • @Phil: Only during the click, as long as i hold mouse click on the button. – Malloc Commented Oct 19, 2012 at 3:47
  • @Malloc Then see Matt's answer below – Phil Commented Oct 19, 2012 at 3:49
Add a ment  | 

3 Answers 3

Reset to default 5

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>

本文标签: javascriptchange the image background of a button when it39s clickedStack Overflow