简体   繁体   English

jQuery CSS禁用原始的悬停样式

[英]jQuery CSS disables the original hover-style

I have a div called "msg_div" and in the styles.css I have a line like this: 我有一个名为“ msg_div”的div,在styles.css中,我有这样一行:

.msg_div:hover { background-color: #eee; }

Now I added this script to a page: 现在,我将此脚本添加到页面中:

$(".msg_div").css("background-color", "#FFF");
$(this).css("background-color", "#EEE");

But now there isn't any hover style anymore. 但是现在没有悬停样式了。 How can I fix this? 我怎样才能解决这个问题?

My intention is that when I click a box, the grey background should switch to the clicked div. 我的意图是,当我单击一个框时,灰色背景应切换为单击的div。

Edit (this is the HTML code): 编辑(这是HTML代码):

<script>
    $(".msg_posteingang_div").click(function(){
        $(".msg_div").css("background-color", "#FFF");
        $(this).css("background-color", "#EEE");
    })
</script>
<div class="msg_div">Message 1</div>
<div class="msg_div">Message 2</div>
<div class="msg_div">Message 3</div>
<div class="msg_div">Message 4</div>

Edit 2: The solution is to create a style (in styles.css) for the .msg_div class itself not just for the :hover . 编辑2:解决方案是为.msg_div类本身而不是:hover创建样式(在styles.css中)。

My styles.css now: 我现在的styles.css:

.msg_div { padding:5px; cursor: pointer; }
.msg_div:hover { background-color: #eee; }

you are using msg-div in your css. 您在CSS中使用msg-div。 and msg_div in your javascript. 和msg_div在您的JavaScript中。 make sure your elements are named correctly. 确保您的元素名称正确。

Add !important to the hover background-color style: 向悬停background-color样式添加!important

.msg_div:hover { background-color: #eee!important; }

Here is working example: 这是工作示例:

http://jsfiddle.net/e9d5e67c/1/ http://jsfiddle.net/e9d5e67c/1/

Note this solution is the quickest one (but works:)), and you may want to read why this is happening and try a better solution described here: CSS hover selector for background-color not working after dynamic change of background-color with jquery 请注意,此解决方案是最快的解决方案(但可行:)),并且您可能想了解为什么会发生这种情况,并尝试此处描述的更好的解决方案: 使用jQuery动态更改背景颜色后,背景颜色的CSS悬停选择器不起作用

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

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