当我使用这个时,浏览器运行缓慢

the browser goes slowly when i use this

本文关键字:浏览器 运行 缓慢      更新时间:2023-09-26

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(){      
});

我这样做是为了让图像在悬停时随鼠标移动。但浏览器运行缓慢。我该如何解决这个问题?

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

正如用户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/