如何在单击时更改按钮图标

how to change button icon on click?

本文关键字:按钮 图标 单击      更新时间:2023-09-26

我有这个按钮,它有一个图标(图片)。现在,我想做的是点击一个按钮图标(图片)就会变成另一个图标,当你再次点击时,它会跳回到旧图标上。(类似于拨动原理)。

这是我的按钮CSS代码:

.w8-button {
    display: table;
    padding: 7px 15px 8px 15px;
    border: none;
    font-family: "open_sans_lightregular";
    font-size: 13px;
    font-weight: bold;
    cursor: pointer;
    opacity: 0.9;
}

这是CSS图标代码:

.w8-button.iconize {
    padding-right: 50px !important;
    background: url(D:/firstPicture.png) no-repeat 115px center;
}

这就是我在html:中调用按钮的方式

<li>
  <input type="submit" id="w8-d-blue" name="w8-d-blue" class="w8-button iconize" value="Button"/>
</li>

有人能告诉我如何用javascript编写代码吗?当我点击按钮时,图标(背景图片)会改变并保持原样,直到你再次点击为止,它会回到旧的(如切换系统)

在支持addEventListener和ClassListneneneba API的现代浏览器上(它们各自的MDN页面上都提供了垫片,以增加对旧浏览器的支持),您可以这样做。

CSS

.w8-button {
    display: table;
    padding: 7px 15px 8px 15px;
    border: none;
    font-family:"open_sans_lightregular";
    font-size: 13px;
    font-weight: bold;
    cursor: pointer;
    opacity: 0.9;
}
.w8-button.iconize {
    padding-right: 50px !important;
    background: url("http://imageshack.us/a/img856/3817/ticklf.png") no-repeat 5px center;
}
.w8-button.iconize2 {
    padding-right: 50px !important;
    background: url("http://imageshack.us/a/img822/1917/crossn.png") no-repeat 5px center;
}

HTML

<li>
    <input type="submit" id="w8-d-blue" name="w8-d-blue" class="w8-button iconize" value="Button" />
</li>

Javascript

document.getElementById("w8-d-blue").addEventListener("click", function (e) {
    var target = e.target;
    target.classList.toggle("iconize");
    target.classList.toggle("iconize2");
}, false);

在jsfiddle 上

以下是如何在jquery 中做到这一点

$(function(){
  $("#w8-d-blue").click(function(){
     $(this).toggleClass("iconize");
     return true;
  });
});

要使用jquery,您必须将其添加到页面的标题部分:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

然后键入上面的代码。

快速解决方案

var switch = 0, element = document.getElementById("w8-d-blue"), img1, img2;
element.onclick = function(){
            if (switch == 0){
                element.style.backgroundImage(img1);
                switch = 1;
                }
            else {
                        element.style.backgroundImage(img2);
                switch = 0
                }

我想你没有意识到Jquery能给你带来的奇迹。如果是这样的话,你真的应该查一下,它会让很多类似的事情变得容易得多。