简体   繁体   English

CSS图像条纹悬停效果不适用于jQuery

[英]CSS image stripe hover effect not working with jQuery

The title might be a little bit confusing. 标题可能有点令人困惑。 Let me explain my problem: I am using CSS image stripes for social buttons. 让我解释一下我的问题:我使用CSS图像条纹作为社交按钮。 Here is a quick example: 这是一个简单的例子:

.appnet {
     display:block;
     width:64px;
     height:64px;
     background: url('http://yanlu.de/files/images/SocialButtons.svg') no-repeat;
     background-position:-256px 0;
     margin-right: 10px;
     margin-left: 10px;
}
.appnet:hover {
     background-position:-256px -64px;
}
.appnet:active {
     background-position:-256px -128px;
}

Now there is my jQuery part: 现在有我的jQuery部分:

$('.appnet').css('background-position','-256px -192px');

Now, while hovering the button there is no change of the image stripe. 现在,在悬停按钮时,图像条纹没有变化。 Why? 为什么?

That's because you are cascading styles by inline CSS. 那是因为你通过内联CSS级联样式。

Take a look at the example below: 看看下面的例子:

HTML HTML

<a href="">:hover is not working, yea?</a>

CSS CSS

a:hover {
  background-color: gold;
}

a {
  background-color: orange;
}

And finally the JS 最后是JS

$('a').css('background-color', 'lightgreen');

JSBin Demo 1 JSBin演示1

By using jQuery.css(); 通过使用jQuery.css(); method, you add the CSS as inline style to the selected element, which it has a higher priority than internal or external styles. 方法,将CSS作为内联样式添加到所选元素,它具有比内部或外部样式更高的优先级。

You can make the :hover declaration !important to set its priority higher: 你可以使:hover声明!important是将其优先级设置得更高:

a:hover {
  background-color: gold !important;
}

JSBin Demo 2 JSBin演示2

My suggestion would be avoid doing the styling in your Javascript. 我的建议是避免在你的Javascript中做样式。

Instead have a 'dark' class 相反,有一个'黑暗'类

.dark {
    background-position: -256px -192px;
}

And just toggle it on and off as required. 然后根据需要打开和关闭它。

$('.appnet').toggleClass('dark');

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

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