jQuery tooltip follow mouse

2019-03-06 04:55发布

问题:

I've been using this script http://jqueryfordesigners.com/coda-popup-bubbles/

and trying to use this fix to position the bubble according to where the user's mouse is on the page:

$([trigger.get(0), info.get(0)]).mouseover(function (e) {
  if (hideDelayTimer) clearTimeout(hideDelayTimer);
  if (beingShown || shown) {
    // don't trigger the animation again
    return;
  } else {

   // reset position of info box
    beingShown = true;
    info.css({
      top: e.pageY,
      left: e.pageX,
      display: 'block'
    }).animate({
      top: '-=' + distance + 'px',
      opacity: 1
    }, time, 'swing', function() {
      beingShown = false;
      shown = true;
    });
}

Instead of the bubble appearing where the e.pageY and e.pageX of the mouse is, it adds those values in addition to where the trigger is, because the bubble is positioned absolutely inside the relative trigger.

How can I keep the bubble where the mouse is?

回答1:

after the bubble is shown you need to set some function say timeout to update the bubble position according to mouse position.

function:

var x,y;//to track mouse positon
function UpdatePosition(){      
   $(ID_OF_BUBBLE).css({left:x+"px",top:y+"px"});         
   setTimeout("UpdatePosition()",100);
}

you may insert it here:

if (beingShown || shown) {
 //SETUP timeout to a function which updates bubble's position
 setTimeout("UpdatePosition()",100);
return;

add mouse move hook to get position:

$(document).ready(function(){
    $().mousemove(function(e){
    x=e.pageX ;
    y=e.pageY;
    });
   .......
});

PS:- you may have to tweak position mode of the bubble