【问题标题】:Alternative to .is(":hover")? Doesn't work in Opera.is(":hover") 的替代方案?在 Opera 中不起作用
【发布时间】:2012-08-02 04:40:20
【问题描述】:

http://jsfiddle.net/cgWdF/3/

在所有浏览器中都能正常工作*,最新的 Opera 除外。

*没有在IE9以下测试过

应该指定了,需要返回true或者false,我不是用来绑定事件的。

【问题讨论】:

  • jQuery 的 .hover 处理程序不适合你?
  • 不幸的是,没有。我不能在 if 语句中使用 .hover,这是我需要的。
  • 好吧,无论您需要它做什么,您都可以在该处理程序中使用 .data() 并检查该数据。
  • 我不明白吗?为什么不能只将处理程序绑定到 mouseover 事件。为什么需要为此使用伪类?

标签: javascript jquery hover opera jquery-events


【解决方案1】:

jQuery 的 .hover 在 Opera 12 中工作。

var $sample = $("#sample");
$sample.hover(function() {
   $sample.css("background", "yellow");
}, function() {
    $sample.css("background", "");
});

Fiddle

或者,使用.data 存储悬停状态并对其进行测试(类似于您原来的小提琴):

var $sample = $("#sample");
$sample.hover(function() {
   $(this).data('hovering', true);
}, function() {
   $(this).data('hovering', false);
});

setInterval(function(){
    var $sample = $("#sample");
    if($sample.data('hovering')) {
       $sample.css("background", "yellow");
    }
    else {
       $sample.css("background", "");
    }
}, 200);

Fiddle

【讨论】:

  • 谢谢,这正是我所需要的。
  • 做得很好,我会在附加新的悬停处理程序之前调用.off('hover'),以免将多个悬停事件堆叠到同一元素:fiddle,但从性能方面来说,这不应该是真的直到您将其悬停一百万次而不重新加载页面。 =]
【解决方案2】:

你可以使用 .mouseover() 和 .mouseout() 来达到同样的效果。如果你想延迟动画,你可以在 jQuery UI 中使用 .animate()

$('#sample').mouseover(
        function() {
            $(this).stop().animate({
                backgroundColor: "yellow"}, 200);
        });

$('#sample').mouseout(
        function() {
            $(this).stop().animate({
                backgroundColor: "#aaa"}, 200);
        });

http://jsfiddle.net/cgWdF/8/

【讨论】:

    【解决方案3】:

    从 jQuery 1.9.1 开始,其他浏览器已经赶上了 Opera——它现在也不再适用了。正如您的小提琴所调查的那样,“它”是 .is(":hover")。

    我为 .is(":hover") 写了一个解决方法,见 fiddle http://jsfiddle.net/mathheadinclouds/BxL4w/

    function mouseIsOver(what){
        return $(what).is(":hover");
    }
    function mouseIsOverWorkaround(what){
        var temp = $(what).parent().find(":hover");
        return temp.length == 1 && temp[0] == what;
    }
    function mo(what){
        return document.getElementById("workaround").checked ? mouseIsOverWorkaround(what) : mouseIsOver(what);
    }
    setInterval(function(){
        var theBox = $("#theBox");
        if(mo(theBox[0])) {
           theBox.css("background", "yellow");
        } else {
           theBox.css("background", "");
        }
    }, 200);
    

    和html

    <input type="checkbox" id="workaround"/>
    <div id="theBox"></div>
    

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 2018-04-26
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多