简体   繁体   English

如何使用JS在鼠标移动时将div的中心定位到鼠标光标的中心?

[英]How to position the center of a div to the center of the mouse cursor on mouse movement with JS?

I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements. 我正在尝试将div元素的中心定位到鼠标光标的中心,这将跟随其移动。

Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor. 我已经想出了下面的代码,但是这个代码的问题是,以下div不在光标的中心,而是与光标有一些偏移。

WORKFLOW 工作流程

The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. 我的代码的基本思想是,当鼠标进入.post-entry div元素时,应显示当前项中的.pointer并跟随鼠标的光标。 When the mouse leaves the div it should be hidden. 当鼠标离开div它应该被隐藏。

CODE

HTML post item: HTML发布项目:

<article class="col-md-4 col-sm-6 post-entry">
    <a href="#" title="">
        <figure class="post-thumb">
            <img src="http://placehold.it/300x300" alt="">
            <div class="pointer" style="background: red;"></div>
        </figure><!-- End figure.post-thumb -->
    </a>
</article><!-- End article.col-md-4 post-entry -->

JS: JS:

$('.entry .post-entry').each(function() {
  $(this).on("mouseenter", mouseEnter);
  $(this).on("mousemove", mouseMove);
  $(this).on("mouseleave", mouseLeave);
});


function mouseEnter(event) {

  console.log('enter');

  var target = $(this);
  var dot = target.find('.pointer');

  var mX = (event.clientX);
  var mY = (event.clientY);

  set(
    dot, {
      x: mX,
      y: mY,
      force3D: !0
    }
  );

};


function mouseMove(event) {

  console.log('move');

  var target = $(this);
  var dot = target.find('.pointer');

  // var offset = target.offset();
  // var width = target.width();
  // var height = target.height();
  // var top = offset.top;
  // var left = offset.left;

  var mX = (event.clientX);
  var mY = (event.clientY);

  $(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');

};

function mouseLeave(event) {

  console.log('leave');

    var target = $(this);
    var dot = target.find('.pointer');

    $(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');


};

function onClick(event) {
  event.preventDefault();
  console.log('click');
};

function set(el, obj) {
  var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
  return dot;
};

PROBLEM / DEMO 问题/演示

As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. 如前所述,跨度位于鼠标光标之后,只有跨度没有位于光标的中心。 It will be offset the mouse. 它将偏移鼠标。 See live demo here 在这里观看现场演示

I tried already something like this for the mX and mY variables, but with no succes: 我已经为mX和mY变量尝试过类似的方法,但是没有成功:

var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();

Also the answer from @hiEven doesn't work and will let me with the same issue: @hiEven的答案也行不通,会让我遇到同样的问题:

transform: calc(mX - 50%, mY - 50%)

I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me. 我知道我应该将.pointer除以一半,但是对我来说,如何在代码中实现它是一个很大的问号。

UPDATE 更新

I created two new Codepen projects: 我创建了两个新的Codepen项目:

Use without images: http://codepen.io/anon/pen/GqGOLv . 不带图片使用: http : //codepen.io/anon/pen/GqGOLv When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. 当您将鼠标悬停在第一项上时,您会看到棕色指针正确地位于您的鼠标光标之后-我在寻找什么。 But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item. 但是,将鼠标悬停在第二个上时,只有当您位于项目的最左侧时,您才会看到红色指针。

When I use images: http://codepen.io/anon/pen/QExOkx . 当我使用图像时: http : //codepen.io/anon/pen/QExOkx The problem by this example is that when you at the very top of the first column, you will see the brown pointer. 此示例的问题是,当您在第一列的顶部时,将看到棕色指针。 When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images. 将鼠标悬停在第二个项目的左上角时,您会看到一小部分红色指针,与没有图像的示例相同。

Both pointer should follow the mouse cursor correctly. 两个指针都应正确跟随鼠标光标。 And I am searching for a solution that works with the use of an image. 我正在寻找一种可以使用图像的解决方案。

Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero. 在这两个示例旁边,当我添加到第一个示例时,在第一个项目margin-left增加了一个margin-left ,仅当将其设置为左边空白为零时,棕色指针才会位于鼠标光标的中心。

So I don't know what's missing and why it only works with the first example (without images) and only for the first item? 因此,我不知道缺少什么,为什么它仅适用于第一个示例(无图像)并且仅适用于第一个项目?

I assume you want the circle being center of your mouse, right? 我假设您想让圆圈成为鼠标的中心,对吗?

try do this transform: calc(mx - 50%, my - 50%) 尝试执行以下transform: calc(mx - 50%, my - 50%)

here is the demo 这是演示

Based on my latest update, I did not conform to the correct formula that is needed to center the element .pointer to the mouse. 根据我的最新更新,我不符合将元素.pointer到鼠标所需的正确公式。

In order to use the following calculation within mouseMove: 为了在mouseMove中使用以下计算:

var mX = (event.clientX);
var mY = (event.clientY);

Should be changed to this: 应更改为:

var height = dot.height();
var width = dot.width();

var offset = target.offset();
var w = target.width();
var h = target.height();
var top = offset.top;
var left = offset.left;

var mX = (event.clientX - left) - width / 2 - 15; // 15 = padding
var mY = (event.clientY - top) - height / 2;

So this formule is considering that the following DOM element .pointer will follow the mouse movements of the user. 因此,此公式考虑的是以下DOM元素.pointer将跟随用户的鼠标移动。 I don't know exactly why this working, but the offset from the previous item will be decreased from the current clientX coordinates, so the position of the second item is reset to zero, so the pointer will start at the left side of each item. 我不知道为什么会这样,但是从当前clientX坐标到上一个项目的偏移量将减少,因此第二个项目的位置被重置为零,因此指针将从每个项目的左侧开始。

Here is a working demo of above code: http://codepen.io/anon/pen/AXdxZO?editors=0110 这是上面代码的工作演示: http : //codepen.io/anon/pen/AXdxZO?editors=0110

Try the code below 试试下面的代码

<html>
  <head>
    <style>
          #mouse_div{
            position: absolute;
            background-color: black;
          }
    </style>
    <script>
          var div_width = 100;
          var div_height = 100;
          var div_x, div_y;
          function mouse_position(event){
            var mouse_x = event.clientX;
            var mouse_y = event.clientY;
            document.getElementById("mouse_div").style.width = div_width + "px";
            document.getElementById("mouse_div").style.height = div_height + "px";
            div_x = mouse_x - (div_width / 2);
            div_y = mouse_y - (div_height / 2);
            document.getElementById("mouse_div").style.left = div_x + "px";
            document.getElementById("mouse_div").style.top = div_y + "px";
          }
    </script>
  </head>
  <body onmousemove="mouse_position(event)" onload="mouse_position(event)">
    <div id="mouse_div"></div>
  </body>
</html>

This program gets the position of your mouse, the width, and the height of the div . 该程序获取鼠标的位置, div的宽度和高度。 Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). 然后,它取x并从中减去div的宽度除以2(这将div的x位置居中在鼠标上)。 The program then does the same thing for the mouse y. 然后,程序对鼠标y执行相同的操作。 Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be. 一旦所有的变量的定义,我使用JavaScript访问的div CSS放置div它必须这样做。

Note: you must make sure that the position of the div is set to absolute or the program will not work. 注意:您必须确保div的位置设置为绝对位置,否则程序将无法运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM