简体   繁体   English

单击更改图标图像

[英]Changing an icon image on click

Here is what I want to do. 这是我想做的。 There are four icons, and when we click on an icon, its background image should change. 有四个图标,当我们单击一个图标时,它的背景图像应该改变。 When we click again on it, the first image should come again. 当我们再次单击它时,第一个图像应该会再次出现。 Here is my code. 这是我的代码。 Thanks for your help ; 谢谢你的帮助 ; I spent some time but I didn't find the solution: the "if" block doesn't not recognize the value of the background. 我花了一些时间,但找不到解决方案:“ if”块无法识别背景值。 Thanks a lot for helping me. 非常感谢您的帮助。

<!DOCTYPE html>
<html lang="fr">
    <head>
    <meta charset="utf-8">
    <title>Test</title>
        <style type="text/css">
    #image1, #image2, #image3, #image4 {
    background: url('icon1.png');
        width:24px;
    height:24px;
        }
    </style>
</head>
<body>

    <p id="image1" onclick="change(this)"></p>
    <p id="image2" onclick="change(this)"></p>
    <p id="image3" onclick="change(this)"></p>
    <p id="image4" onclick="change(this)"></p>

    <script type="text/javascript">
    function change(element) {
        if(element.style.background == "url('icon1.png')") {
            element.style.background = "url('icon2.png')";
        } else {
            element.style.background = "url('icon1.png')";
        }
    }       
    </script>

</body>
</html>

The if condition wont probably result as true for the first time as background-image is applied through css class and not inline style. if通过CSS类而不是内联样式应用背景图像,则if条件可能不会首次成为true。

So the solution would be 所以解决方案是

function change(element) {
  var imgURL = window.getComputedStyle(element).getPropertyValue("background-image");
  if(imgURL == "url('icon1.png')") {
    element.style.background = "url('icon2.png')";
  } else {
    element.style.background = "url('icon1.png')";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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