首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jQuery将元素与鼠标位置对齐有一个偏移量

使用jQuery将元素与鼠标位置对齐有一个偏移量
EN

Stack Overflow用户
提问于 2016-09-23 05:18:51
回答 2查看 51关注 0票数 0

我正在开发一个映射特性,将元素与鼠标位置对齐的jQuery脚本的偏移量似乎与页面间距相匹配。

这是测试区域http://champagnecentre.com/dev/directory/

代码语言:javascript
复制
jQuery(document).mousemove(function(e){
   jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});
EN

回答 2

Stack Overflow用户

发布于 2016-09-23 07:35:40

@Bwolfing是对的,我相信。e.pageYe.pageX与文档相关。因为你的div是嵌套的,所以topleft的位置是相对于父级的,这导致了偏移量。

通过使用.parent().offset(),我们可以计算出偏移量,小提琴如下。我已经添加了.area作为替换的div,在其中嵌套.directory-listing.mousemove函数可以归因于$(document)...$('.area')...,请注意,将.mousemove编写为.on的主题会更好

代码语言:javascript
复制
$(document).on({
  mouseenter: function(e) {
    // special effects
  },
  mousemove: function(e) {
    e.preventDefault();
    var target = $('.directory-listing'),
      d = target.parent().offset(), // this gets the offset positions
      dX = d.left + 6,
      dY = d.top + 12; // the +6 and +12 here are just to center the 'x'
    target.css({
      left: e.pageX - dX,
      top: e.pageY - dY
    });
  },
  mouseleave: function(e) {
    // special effects
  },
  click: function(e) {
    // special effects
  }
});
代码语言:javascript
复制
.area {
  position: absolute;
  left: 10%;
  top: 100px;
  width: 40%;
  height: 50%;
  background: #bbb;
  border: 1px solid #09f;
}
.directory-listing {
  position: absolute;
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div class="area">
  <div class="directory-listing">X</div>
</div>

票数 1
EN

Stack Overflow用户

发布于 2016-09-23 05:38:08

编辑:根据@Bwolfing下面的评论,我对规范的解释是不正确的。我已经更新了下面的plunk,为上面提出的建议提出了一个替代解决方案。将工具提示的位置更改为fixed会强制它相对于页面。

https://plnkr.co/8CCns5mwdqSoWiGK1SDN

HTML

代码语言:javascript
复制
<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@2.2.4" data-semver="2.2.4" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="offsetWrapper">
      <h1 id="myH1">Hello Plunker!</h1>
    </div>
  </body>

</html>

JS

代码语言:javascript
复制
$(document).on ('mousemove', function (event)
{
  $('#myH1').css ({'left', event.pageX, 'top', event.pageY});
});

CSS

代码语言:javascript
复制
#myH1 {
  position: fixed;

  margin: 0;
}

.offsetWrapper {
  position: relative;
  left: 100px;
  top: 100px;

  /*Show the position of the container for reference*/
  background-color: red;
  height: 10px;
  width: 10px;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39649039

复制
相关文章

相似问题

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