根据鼠标的位置对齐盒子的x,y位置

时间:2013-10-05 07:32:45

标签: javascript jquery

我的网页上有几个图像,我想在鼠标访问图像时显示一个框(有关图像的更多信息)。我还希望盒子位置正好在鼠标所在的位置,并且随着鼠标的移动而移动。这是我的代码,但它不起作用。问题出在Firefox中,盒子和鼠标垂直对齐(不是水平对齐),但在Chrome盒子和鼠标中水平对齐(不是垂直对齐)

<div class="library_teaser_photo_class">
<div class="book_detail" style="display:block;visibility :hidden;position: fixed;">
<?php print $fields['field_library_writer']->content; ?> 
</div>
<?php print $fields['field_library_photo']->content; ?>
</div>

这是jQuery代码

var offsetX = 10;
var offsetY = 20;
$('.library_teaser_photo_class').hover(function(e)
{
if (e.pageX || e.pageY) 
    {
    posx = e.pageX;
    posy = e.pageY;
}
else if (e.clientX || e.clientY)    
    {
     posx = e.clientX + document.body.scrollLeft
                          +   document.documentElement.scrollLeft;
     posy = e.clientY + document.body.scrollTop
                          +document.documentElement.scrollTop;
}
    $(this).find('.book_detail').css('visibility','visible')
                                .css('top',posy + offsetY)
                    .css('left',posx + offsetX);
},function(){
        $(this).find('.book_detail').css('visibility','hidden');
});

$('.library_teaser_photo_class').mousemove(function(e){
    if (e.pageX || e.pageY)
            {
          posx = e.pageX;
          posy = e.pageY;
    }
    else if (e.clientX || e.clientY) 
            {
    posx = e.clientX+document.body.scrollLeft
                             +document.documentElement.scrollLeft;
    posy = e.clientY + document.body.scrollTop
                             +document.documentElement.scrollTop;
}
$(this).find('.book_detail').css('top',posy ).css('left',posx );
});

1 个答案:

答案 0 :(得分:0)

var mouseX;
    var mouseY;
    $(document).mousemove( function(e) {
       mouseX = e.pageX; 
       mouseY = e.pageY;
    });  
    $('.library_teaser_photo_class').mouseover(function(){
      $(this).find('.book_detail').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,

    $('.library_teaser_photo_class').mouseout(function(){
     $(this).find('.book_detail').fadeOut('slow');
    });

If you DIV is already positioned, you can simply use

    $('.library_teaser_photo_class').hover(function(){
      $(this).find('.book_detail').fadeIn('slow');
    });

另外,请注意,您的DIV样式需要设置为display:none;才能淡入或显示。