How do you add pseudo classes to elements using jQuery?

别来无恙 提交于 2019-11-26 17:49:11

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.

chanjarster

I think there is no way to do that with jQuery or javascript.

You can find the same answer in these two questions:

  1. setting-css-pseudo-class-rules-from-javascript
  2. css-pseudo-classes-with-jquery

Make a div on the page

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

And then programmatically hardcode the style, i.e.,

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

Unfortunately, the element you are calling this will have to have an 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!