How to apply jQuery to .element:before:hover?

2019-09-08 08:45发布

问题:

I'm using slick slider, but for whatever the reason when I move mouse over a next or previous button it doesn't change the opacity (mouse-out: 0.5, mouse-in: 1) and it just stays 1, is there a way I could apply jQuery to change the CSS for this task? The elements I want to add jQuery to are shown below:

.slick-prev:hover:before,
.slick-prev:focus:before,
.slick-next:hover:before,
.slick-next:focus:before
{
    opacity: 1;
}

.slick-prev:before,
.slick-prev:before,
.slick-next:before,
.slick-next:before
{
    opacity: 0.5;
}

回答1:

(function($) {
  jQuery.fn.extend({
    // get pseudo property
    getPseudo: function(pseudo, prop) {
      var props = window.getComputedStyle(
        $(this).get(0), pseudo
      ).getPropertyValue(prop);
      return String(props);
    },
    // set pseudo property
    setPseudo: function(_pseudo, _prop, newprop) {
      var elem = $(this);
      var s = $("style"); // existing `style` element
      var p = elem.getPseudo(_pseudo, _prop); // call `getPseudo`
      var r = p !== "" ? new RegExp(p) : false;
      var selector = $.map(elem, function(val, key) {
        return [val.tagName
                , val.id 
                  ? "#" + val.id : null
                , val.className ? "." + val.className : null]
      });
      var _setProp = "\n" + selector.join("")
        .toLowerCase()
        .concat(_pseudo)
        .concat("{")
        .concat(_prop + ":")
        .concat(newprop + ";}"); // css semicolon
      return ((!!r ? r.test($(s).text()) : r) 
              ? $(s).text(function(index, prop) {
                  return prop.replace(r, newprop)
                }) 
              : $(s).append(_setProp)
      );
    }
  })
})(jQuery);

$(".show-more-after").on("click", function() {
  var toggle = $(this).getPseudo(":after", "opacity");
  $(this).setPseudo(":after", "opacity", toggle === "0.5" ? "1" : "0.5");
})
.show-more-after:after {
    content: " abc";
    opacity : 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="show-more-after">click</div>



回答2:

In short: No, you can't.

Detailed answer:

The elements you are using are called pseudo-elements (:before, :after, etc). They are not present in the DOM, so you can't select either of them and change their style.

A possible workaround:

Override that styles by declaring another rules of style for the same elements (for example, by injecting a STYLE tag which contains the styles which will override the existing one).