你如何将伪类添加到使用jQuery的元素?

在CSS中,将鼠标hover在元素上时,可以使用:hover伪类为其指定视图:

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

你怎么能使用jQuery添加或“打开”这个伪类? 通常在jQuery中,如果你想添加一个类,你应该这样做:

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

我试过“hover”,但是这个字面上增加了一个名为“hover”的类到元素。

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

你不能强制使用jQuery来应用某个伪类。 这不是如何伪类(尤其是dynamic伪类)的工作,因为他们被devise为基于不能通过DOM( 规范 )expression的信息进行select。

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

 .element_class_name:hover, .element_class_name.jqhover { /* stuff here */ } $(this).addClass("jqhover"); 

或者,您可以search.element_class_name:hover规则,并使用jQuery自己添加该类,而不将其硬编码到您的样式表中。 不过,这是一样的原则。

我认为没有办法用jQuery或JavaScript做到这一点。

你可以在这两个问题中find相同的答案:

  1. 设置CSS的伪类的规则从JavaScript的
  2. CSS-伪类与- jQuery的

在页面上创build一个div

 <div id="Style"> <style> .element_class_name:hover { /* stuff here */ } </style> </div> 

然后以编程方式硬编码样式,即,

 $("#Style").find("style").prepend("#" + this.id + ":hover, "); 

不幸的是,你所调用的这个元素必须有一个id。

 $("body").children().click(function(){ $("#Style").find("style").prepend("#" + this.id + ":hover, "); }); 
 /* demo */ * { transition: opacity 1s; } 
 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <div id="Style"> <style> .element_class_name:hover { opacity: 0 !important; } </style> </div> <button id="btn1">Add hover class here</button> <button id="btn2">Add hover class here too</button> <p id="Note"> To use this though, you'll have to assign an id to that particular element though. </p> </body> </html>