将光标保持在图像的中心,图像跟随

问题描述 投票:0回答:1

我有一个舞台(id="box"),当光标在这个舞台上移动时,一个红色圆圈会随着光标移动。 一切都按预期进行,但光标位于红色圆圈之外。

我尝试让光标停留在圆的中心,但还没有成功。

如有任何帮助,我们将不胜感激!

$("#box").mousemove( function(e) {
  $popup = $(this).find(".circle").first();
  var eTop = $(this).offset().top;
  var eLeft = $(this).offset().left; 
  var x = e.pageX;
  var y = e.pageY;
 // console.log("pageX: " + x);
 //  console.log("pageY: " + y)
  $(this).find(".circle").css({top: y - eTop, left: x - eLeft });

});
#box {
  width:500px;
  height:200px;
  display:block;
  background: green;
  position:relative;

}


.circle {
      position: absolute;
    z-index: 100;
    overflow:hidden;
    white-space: nowrap;
    border: 1px solid red;
    width: 100px;
    height: 100px;
    border-radius: 100%
}

#box .circle {visibility: hidden;}
#box:hover .circle {visibility: visible;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div id="box">
    <div class="circle"></div>
    </div>

html jquery css
1个回答
0
投票

您忘记从坐标中减去圆半径:

$("#box").mousemove( function(e) {
  $popup = $(this).find(".circle").first();
  var eTop = $(this).offset().top;
  var eLeft = $(this).offset().left; 
  var x = e.pageX;
  var y = e.pageY;
 // console.log("pageX: " + x);
 //  console.log("pageY: " + y)
  $(this).find(".circle").css({top: y - eTop - 50, left: x - eLeft - 50});

});
#box {
  width:500px;
  height:200px;
  display:block;
  background: green;
  position:relative;

}


.circle {
      position: absolute;
    z-index: 100;
    overflow:hidden;
    white-space: nowrap;
    border: 1px solid red;
    width: 100px;
    height: 100px;
    border-radius: 100%
}

#box .circle {visibility: hidden;}
#box:hover .circle {visibility: visible;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div id="box">
    <div class="circle"></div>
    </div>

© www.soinside.com 2019 - 2024. All rights reserved.