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

Using jQuery to align an element to mouse location has an offset

本文关键字:鼠标 位置 有一个 偏移量 对齐 jQuery 元素 使用      更新时间:2023-09-26

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

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

jQuery(document).mousemove(function(e){
   jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});

@Bwolfing是对的。e.pageYe.pageX与文档相关。当你的div嵌套时,topleft的位置是相对于父元素的,这导致了偏移。

通过使用.parent().offset(),我们可以锻炼偏移量,如下所示。我将.area添加为移位的div,其中嵌套.directory-listing, .mousemove函数可归因于$(document)...$('.area')...,请注意,.mousemove最好编写为.on的主题:

$(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
  }
});
.area {
  position: absolute;
  left: 10%;
  top: 100px;
  width: 40%;
  height: 50%;
  background: #bbb;
  border: 1px solid #09f;
}
.directory-listing {
  position: absolute;
}
<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>

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

https://plnkr.co/8CCns5mwdqSoWiGK1SDN

<!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

$(document).on ('mousemove', function (event)
{
  $('#myH1').css ({'left', event.pageX, 'top', event.pageY});
});
CSS

#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;
}