首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据鼠标所在位置对齐框的x,y位置

问根据鼠标所在位置对齐框的x,y位置
EN

Stack Overflow用户
提问于 2013-10-05 15:32:45
回答 1查看 112关注 0票数 1

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

代码语言:javascript
复制
<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代码

代码语言:javascript
复制
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 );
});
EN

回答 1

Stack Overflow用户

发布于 2013-10-05 15:45:09

代码语言:javascript
复制
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;,才能使其显示为fadeIn。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19195243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档