开发者

What is the best way to a div on mousemove() in jquery?

In my MVC application I have a view with the following DOM:

<div class="item">
Item Name
</div>

These “item divs” are generated via a foreach loop inside the view. My goal is show another "div" on mouse move event, which will offer the user some options (like, share, delete.. etc.). I don't have a specific design in mind for the “options d开发者_如何学JAVAiv”. But my question is what the best to achieve this is? Should I be creating the “options div” right next to the “item div” through in the foreach loop and set the visibility in the css on mouse move? I tried that, and it really did hurt the performance.

PS: I have around 2000 “Item divs”.

Thanks!


Chances are you don't actually want mousemove, but instead mouseover and mouseout.

mousemove fires many many times in rapid succession, because it fires every time the mouse moves even a small amount while over the element - even if the mouse stayed over the same element. Since it sounds like you just want to set things showing or hidden dependent on which element the mouse is currently over, you can use mouseover and mouseout to do so much more efficiently - show the corresponding links on mouseover, and hide them on mouseout.


This is a tricky one, so I can only give you suggestions. Its more about the optimization than anything else when you have 2000 DOM elements that need an event each.

  1. Use only one option div and move it to the appropriate spot on your event. In the DOM I'd place this options div before your item set.
  2. You will have a huge performance impact if you try to give 2000 elements a hover event. This may be what you noticed before.
  3. Because of #2 consider using a different event like click (or right click) which you can attach to the overall parent of the item set that can act as a delegate. Look for "javascript event delegation" on Google to see examples. This is a common way of improving performance with eventing and huge DOM trees.
  4. An alternate way to increase performance if you absolutely must have a hover event is to simply page your items

Hope that helps


well, you could add the options when hover... (something like when options are needed add it)

$('.item').hover(function(){
   var options = $(this).find('.options');
   if (options.length) { // check if option div is found
       options.show(); // show the option found
   } else { // if no option div found, create one then show it...
       options = $('<div class="options"></div>').appendTo($(this));
   }
}, function(){
   $(this).find('.options').hide(); // on mouseout, hide option div...
});

well, this is just a rough example....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜