javascript - 以选择器 ^= 开头的 css 在使用 javascript 更改类后不起作用

标签 javascript jquery html css css-selectors

将页面加载到浏览器时,一切看起来都很好,背景图像也是正确的。但是,当我单击该图标并且 javascript 将图标的类更改为 .icon-myapp-cow 时,来自 [class^="icon-myapp"] 的 css 将被忽略。仅应用来自 icon-myapp-cow 的 css。在 chrome 和 IE9 中测试

我的CSS

[class^="icon-myapp"] {
    background-image: url("../img/myapp-icons.png");
}

.icon-myapp-horse {
    background-position: -1px -1px;
    height: 15px;
    width: 15px;
}

.icon-myapp-cow {
    background-position: -51px -1px;
    height: 15px;
    width: 15px;
}

我的html

<i class="icon-myapp-horse icon-clickable"></i>

我的javascript

$(".icon-clickable").click(function() {
    $(this).removeClass("icon-myapp-horse");
    $(this).addClass("icon-myapp-cow");

});

最佳答案

您需要将 [class^="icon-myapp"] 更改为:

[class*="icon-myapp"]

参见 here有关更多信息,请在此处获取 fiddle

[attr^=value] Represents an element with an attribute name of attr and whose value is the (sic) prefixed by "value".

[attr*=value] Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

关于javascript - 以选择器 ^= 开头的 css 在使用 javascript 更改类后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20607722/

相关文章:

javascript - 将 Google map 数据导入 iPhone

javascript - jquery数据属性不解析json字符串

javascript - JSF 表单 - 提交 > 关注选定的输入

javascript - 隐藏其子元素后如何纠正元素的高度?

javascript - 将鼠标悬停在任一选择器上即可显示 div

javascript - 动态更改 CSS AngularJS

javascript - 单击 &lt;input type ="submit"> 元素时,JQuery .on(click) 事件处理程序不会停止提交

c# - 图片按钮作为默认按钮

javascript - JS中 "?${new Date().getTime()} "如何更新图像

html - 如何(以及如何不)加载使用@font-face 的 css 文件