当我使用它时,浏览器会变慢

时间:2014-07-29 13:36:21

标签: javascript jquery html css3 browser

HTML:

<a class="myAnchor">asd1<img class="imagenmangue" alt="" src="/images/asd1.jpg" height="215" width="430""></a>

的CSS:

a.myAnchor img{visibility:hidden}
a.myAnchor:hover img{visibility:visible}

脚本:

/*  move the image  */
$('.myAnchor').hover(function(){     
  $(document).on( "mousemove", function( event ) {
  if ($( document ).width() > 800) {
     $(".imagenmangue").css({left: (event.pageX - $('.tabs_type_2').offset().left + 15),top: (event.pageY - $('.tabs_type_2').offset().top - 35)});
  }  else {
 };
});
}, function(){      
});

我正在这样做,所以当图像在a:hover上时,图像会随着鼠标移动。但浏览器进展缓慢。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

每次将鼠标悬停在元素上时,您都会向文档添加新的事件侦听器!你正在超载mousemove。您只想添加一个mousemove事件。完成后删除事件或添加事件一次,并在希望它运行时设置标志。

答案 1 :(得分:0)

正如用户epascarello所指出的,您可以将事件监听器一次附加到元素本身,而不是每次悬停.myAnchor时向文档添加新的事件监听器。所以不要像这样声明:

/* Every time .myAnchor gets hovered */
$('.myAnchor').hover(function(){     
    /* Create a new event listener that listens to the mouse movements inside the document */
    $(document).on( "mousemove", function( event ) {
        /* do stuff here */
    });
});

您可以这样声明:

/* When the mouse moves over .myAnchor */
$(document).on( "mousemove", ".myAnchor", function( event ) { 
    /* do stuff here */
}

我已经创建了一个JSFiddle,更深入地解释了代码中发生了什么,你可以在这里查看:http://jsfiddle.net/M7bWS/