将切换类应用于图像元素

时间:2016-03-27 04:36:02

标签: html css

我正在构建一个Ionic应用程序,我想点击图像并使用不同的图像进行更改。这是一个切换功能。

我有以下课程:

img{
&.default {
  background-image: url("img/726-star.png");
  &.activated{
    background-image: url("img/726-star-selected.png");
  }
}

我应用如下所示的课程:

<img class="default" style="width:38px;height:38px;margin-top:30px;"/>

但是,当我在Chrome调试器工具中看到时,我看不到正在应用的默认类。我究竟做错了什么?

更新:所以,我现在使用的是DIV而不是图像,但是我没有看到div中显示的图像:

#favImage {
  &.default { 
    background-image: url("img/726-star.png"); 
  } 
  &.activated { 
    background-image: url("img/726-star-selected.png"); 
  } 
}
<div id="favImage" class="default" style="width:38px;height:38px;margin-top:30px;"></div>

1 个答案:

答案 0 :(得分:0)

首先,我建议你在html中将你的风格体现为css文件。 第二,如果你使用img标签,别忘了将src属性插入img标签,其他方面img将不会显示。 通过点击它来改变图像我使用通过在img标签“onclick”上写一个属性激活的JavaScript函数并调用JavaScript函数。 函数将图像id转换为变量,并使用匹配方法检查图像src是否包含字符串“726-star-not”,如果不是图像src变为“726-star-selected”,反之亦然。 / p>

to learn more about the match method

function myFunction() {
     
    var image = document.getElementById('favImage');
    
    if (image.src.match("726-star-not")) {
        image.src = "img/726-star-selected.png";
    } else {
        image.src = "img/726-star-not.png";
    }

}
#favImage{
    width:38px;
    height:38px;
    margin-top:30px;
}
<html>
    <head>
        <link rel="stylesheet" href="css/style.css"/>
        <script src="js/javascript.js"></script>
              
    </head>
    <body>
        <img id="favImage" src="img/726-star-not.png" onclick="myFunction()">
    </body>
</html>

相关问题