.is(“:hover”) is broken as of jQuery 1.9 How to fi

2019-01-14 08:25发布

问题:

When doing $(...your selector here...).is(":hover"), jQuery prior to 1.9.1 gave correct answer, while jQuery 1.9.1 tells you this:

Error: Syntax error, unrecognized expression: unsupported pseudo: hover

Here is a workaround (answering not necessary.)

http://jsfiddle.net/mathheadinclouds/V342R/

short answer, check whether

.parent().find(":hover")

has length 1, and contains the element in question.

This is not about performing an action on hover - for that, just use .hover() This is about, at an arbitrary point in time, finding out whether or not some element is being hovered

回答1:

Assuming your selector is #myid, use $('#myid:hover') instead of using .is().

If you are using $(this) or a variable, use myVar.filter(':hover').



回答2:

However the workaround above is unsuitable when you are comparing elements using jQuery.fn.is() with a composed selector which is not known beforehand, and that could match several elements in the parent container.

eg, the same exception is thrown when selectorText in style_get() below is equal to: ".mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar"

..because hover is not defined in Sizzle.selectors.pseudos or Sizzle.selectors.setFilters (jquery-2.1.4, line 1764)..

function style_get(elem) {

  var sheets=document.styleSheets;
  var css_properties={};
  elem=$(elem);

  for (var s in sheets) {
    var rules=sheets[s].rules || sheets[s].cssRules;

    for (var r in rules) {
      if (elem.is(rules[r].selectorText)) {

        css_properties=$.extend(
          css_properties,
          css.parse(rules[r].style),
          css.parse(elem.attr('style'))
        );

      }
    }

  }

  return css_properties;

}


回答3:

Try to give anonymous function into .filter()

I think, my solution will help you:

//
// jQuery 3 pseudo ':hover' doesn't support
//

// Working on jQuery 1.7.1
$("*").on('click', $.proxy(function() {
    if ( this.$('.tooltip:hover').length > 0 ) { // jQuery 3.2.1 -> Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
      console.log('Hovered!');
    } else { 
      console.log('Where is my element!?'); 
    }
}, this));


// Updated solution for jQuery 1.7.1 - 3.2.1
$("*").on('click', $.proxy(function() {
    var isHovered = $('.tooltip').filter(function() {
        return $(this).is(":hover");
    });

    if ( isHovered.length > 0 ) {
      console.log('Hovered!');
    } else { 
      console.log('Where is my element!?'); 
    }
}, this));

also, you can see my GitHub gist:https://gist.github.com/antydemant/74b00e27790e65f4555a29b73eea7bb2



标签: jquery hover