如何在HTML中单击时更改按钮图像

时间:2015-09-07 18:34:25

标签: html css image button

单击按钮时,如何制作按钮的图像将会改变?

   #button {
    text-align:center;
    float:left;

    }

   #button:focus {
    text-align:center;
    float:left;
    background-image: url('qmb2.png');

    }


   <input type="image" src="qmb.png" name="saveForm" class="btTxt submit" id="button" height="49.5px" padding = "0px" />

3 个答案:

答案 0 :(得分:1)

使用jQuery

&#13;
&#13;
$("#flowers").click(function () {
    var _this = $(this);
    var current = _this.attr("src");
    var swap = _this.attr("data-swap");
    _this.attr('src', swap).attr("data-swap",  current);
   
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id='flowers' class="full" src='http://www.rachelgallen.com/images/snowdrops.jpg' width="500" height="400" data-swap='http://www.rachelgallen.com/images/daisies.jpg'  width="500" height="400" />
&#13;
&#13;
&#13;

使用Javascript

&#13;
&#13;
img{height:400px; width:500px}
&#13;
<script>
    function swap()
{
    if (document.pic.src=='http://www.rachelgallen.com/images/snowdrops.jpg'){

document.pic.src='http://www.rachelgallen.com/images/daisies.jpg';
} 
else if (document.pic.src=='http://www.rachelgallen.com/images/daisies.jpg'){

document.pic.src='http://www.rachelgallen.com/images/snowdrops.jpg';
}
}
</script>
<img src="http://www.rachelgallen.com/images/snowdrops.jpg" name="pic" onclick="swap()"/>
&#13;
&#13;
&#13;

使用纯鼠标悬停/ mouseout

&#13;
&#13;
img{height:400px; width:500px}
&#13;
<img src="http://www.rachelgallen.com/images/daisies.jpg" 
onMouseOver="this.src='http://www.rachelgallen.com/images/snowdrops.jpg';"
onMouseOut="this.src='http://www.rachelgallen.com/images/daisies.jpg';">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是纯JavaScript,如果JQuery是不可能的......

<input type="image" id="button" name="img" src="firefox.ico" width="50" />
<script>
    document.getElementById("button").addEventListener("click", function(){
        this.setAttribute("src", "chrome.ico");
    });
</script>

并不是说我对Rachel在纯JavaScript使用方面的答案有所反对,但我觉得可能会有一些更易于读者阅读的内容来切换图像,例如:

document.getElementById("button").addEventListener("click", function(){
    var path;
    if(this.getAttribute("src") === "firefox.ico")
        path = "chrome.ico";
    else
        path = "firefox.ico";
    this.setAttribute("src", path);
});

IMO有点清洁,我们不建议在html中使用onclick属性,而是通过JavaScript实现监听器。

答案 2 :(得分:0)

Jquery,当您第一次单击时,将添加cliked类。

$(document).ready(function(){
$('button').on('click', function(){
$(this).toggleClass('clicked');
});
});

和css:

Button{
Background: img1.jpg;

}
Button.clicked{
Background: img2.jpg;
}