如何使用jQuery添加伪类到元素? [英] How do you add pseudo classes to elements using jQuery?

查看:2675
本文介绍了如何使用jQuery添加伪类到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CSS中,当您将鼠标悬停在元素上时,可以使用:hover伪类指定视图:

  .element_class_name:hover {
/ * stuff here * /
}

如何使用jquery添加或打开这个伪类?通常在jQuery中,如果你想添加一个类,你会这样做:

  $(this).addClass(class_name); 

我尝试了hover,但这个字面上添加了一个名为hover的类。 / p>

如果有人知道写什么,请让我知道!谢谢!

解决方案

您不能强制某个伪类使用jQuery来应用。这不是伪类(尤其是动态伪类)如何工作,因为它们被设计为基于不能通过DOM表达的信息进行选择( spec )。



您必须指定要使用的另一个类,然后使用jQuery添加该类。像这样:

  .element_class_name:hover,.element_class_name.jqhover {
/ * stuff here * /
}

$(this).addClass(jqhover);

或者,您可以搜索 .element_class_name:hover 规则,并使用jQuery本身添加该类,而不将其硬编码到您的样式表。这是同样的原则,


In CSS, when you hover your mouse over an element, you can specify views for it using the :hover pseudo class:

.element_class_name:hover {
    /* stuff here */
}

How can you use jquery to add or "turn on" this pseudo class? Typically in jQuery if you want to add a class you would do:

$(this).addClass("class_name");

I have tried "hover" but this literally adds a class named "hover" to the element.

If anyone knows what to write, please let me know! Thanks!

解决方案

You can't force a certain pseudo-class to apply using jQuery. That's not how pseudo-classes (especially dynamic pseudo-classes) work, since they're designed to select based on information that cannot be expressed via the DOM (spec).

You have to specify another class to use, then add that class using jQuery instead. Something like this:

.element_class_name:hover, .element_class_name.jqhover {
    /* stuff here */
}

$(this).addClass("jqhover");

Alternatively you could hunt for the .element_class_name:hover rule and add that class using jQuery itself, without hardcoding it into your stylesheet. It's the same principle, though.

这篇关于如何使用jQuery添加伪类到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆