How do I position a div relative to the mouse pointer using jQuery?

前端 未结 4 632
天命终不由人
天命终不由人 2020-12-23 10:51

Suppose I have one link in my page and I want that when I place my mouse just over the link, a div will show there according to mouse x,y.

How can I accomplish this

4条回答
  •  攒了一身酷
    2020-12-23 11:29

    var mouseX;
    var mouseY;
    $(document).mousemove( function(e) {
       mouseX = e.pageX; 
       mouseY = e.pageY;
    });  
    $(".classForHoverEffect").mouseover(function(){
      $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
    });
    

    the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,

    $(".classForHoverEffect").mouseout(function(){
      $('#DivToShow').fadeOut('slow');
    });
    

    If you DIV is already positioned, you can simply use

    $('.classForHoverEffect').hover(function(){
      $('#DivToShow').fadeIn('slow');
    });
    

    Also, keep in mind, your DIV style needs to be set to display:none; in order for it to fadeIn or show.

提交回复
热议问题