I want to implement a floating information pop-up (or how to call it), that appears when the cursor is over an element and stays within a fixed distance to the cursor. For instance something more less like here:
http://www.nytimes.com/interactive/2008/09/15/business/20080916-treemap-graphic.html
Say, I have 100 divs for which I want the pop-up to appear. I thought about doing it in two ways:
For each div, in HTML code I have a hidden pop-up div, on
mousemove
I show it, move 开发者_StackOverflow社区to the cursor's position and onmouseleave
I hide it. Each div has itsmousemove
(x100) andmouseenter
event bound (x100).I have a single
mousemove
for the main area of the page,for each div onmouseenter
andmouseleave
I show / hide a pop-up. There is a singlemousemove
(x1) andmouseenter
+mouseleave
for each div (x100).
My questions are:
Is This The Way? Or there is some better jQuery mechanism to use?
Is there any difference in performance when I have a single
mousemove
and 100mousemove
callbacks?
floating information pop-up (or how to call it)
these are called tooltips (there are many javascript/jQuery plugins for these)
in regards to rolling your own, you seem to have it figured out, you'll need to create mouseover
/mousemove
/mouseout
events for the divs. With jQuery this would look something like:
var $tooltip = $('#tooltip'), // reusable jQuery obj
offset = {x: 20, y: 20}; // tooltip offset from the cursor
$('#container div').mouseover(function() { // over
$tooltip.show()
}).mousemove(function(e) { // move
// set the positioning with offset
$tooltip.css({left: e.pageX + offset.x, top: e.pageY + offset.y})
// set the tooltip HTML contents
$tooltip.html('[your content]');
}).mouseout(function() { // out
$tooltip.hide();
});
example jsfiddle
As for performance: jsperf - mousemove parent vs children
setting the mousemove
event on the container does indicate a faster operations/sec in the above test case but in real world use it's unlikely you'd notice a difference.
here's an example where only the container's mousemove
event is set
example jsfiddle #2
Have you just considered using premaid plugin for jquery like qTip ? http://craigsworks.com/projects/qtip2/download
精彩评论