-->

你怎么伪类添加到使用jQuery的元素?(How do you add pseudo classes

2019-06-18 10:54发布

在CSS中,当你将鼠标悬停在一个元素,您可以指定使用的意见吧:hover伪类:

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

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

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

我曾尝试“盘旋”,但这个从字面上增加了一个名为“悬停”的元素类。

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

Answer 1:

你不能强迫某个伪类使用jQuery申请。 这不是伪类(尤其是动态伪类)是如何工作的,因为他们设计了一种基于无法通过DOM(来表示信息,选择规范 )。

你必须指定其他类中使用,然后添加使用jQuery而不是类。 事情是这样的:

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

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

另外,您可以猎取.element_class_name:hover规则,并添加使用jQuery本身类,没有硬编码到您的样式表。 这是同样的原理,虽然。



Answer 2:

我觉得没有办法做到这一点与jQuery或JavaScript。

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

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


Answer 3:

使页面上的一个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> 



文章来源: How do you add pseudo classes to elements using jQuery?