如何使用jQuery相对于鼠标指针定位div? [英] How do I position a div relative to the mouse pointer using jQuery?

查看:129
本文介绍了如何使用jQuery相对于鼠标指针定位div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的页面上有一个链接,我希望当我将鼠标放在链接上时,一个div将根据鼠标x,y显示在那里.

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.

如何使用jQuery完成此操作?

How can I accomplish this using jQuery?

推荐答案

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');
});

上面的功能将使DIV出现在链接可能出现在页面上的任何位置.当链接悬停时,它会慢慢消失.您也可以改用.hover(). DIV将从那里停留,因此,如果您希望当鼠标移开时DIV消失,那么

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');
});

如果DIV已定位,则只需使用

If you DIV is already positioned, you can simply use

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

此外,请记住,您的DIV样式需要设置为display:none;以便淡入或显示.

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

这篇关于如何使用jQuery相对于鼠标指针定位div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆