onClick获取第二个元素,而不是第一个

时间:2018-11-14 16:27:59

标签: javascript html css mouseevent

我创建了跟随鼠标的div。现在,每当我单击e.target等于此div#moveItem。

我不能使用自定义光标,因为宽度将超过128px。

有没有办法绕过这个div并落后目标?

var item = document.querySelector("#moveItem");
var itemRect = item.getBoundingClientRect();

function followMouse(e) {
  var xPos = e.pageX - itemRect.width / 2;
  var yPos = e.pageY - itemRect.height / 2;

  item.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}

function click(e) {
  console.log(e.target);
}

document.addEventListener("mousemove", followMouse, false);
document.addEventListener("mousedown", click, false);
body {
  min-width: 100%;
  min-height: 100%;
}

#moveItem {
  width: 75px;
  height: 75px;
  background-color: tomato;
  position: absolute;
  border-radius: 50%;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Follow Mouse</title>
</head>

<body>
  <div id="moveItem"></div>
</body>

</html>

1 个答案:

答案 0 :(得分:2)

您正在为鼠标后面要忽略的div寻找pointer-events:none

var item = document.querySelector("#moveItem");
var itemRect = item.getBoundingClientRect();


function followMouse(e) {
  var xPos = e.pageX - itemRect.width / 2;
  var yPos = e.pageY - itemRect.height / 2;

  item.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}

function click(e) {
  console.log(e.target);
}

    document.addEventListener("mousemove", followMouse, false);
    document.addEventListener("mousedown", click, false);
body {
  min-width: 100%;
  min-height: 100%;
}
#moveItem {
  width: 75px;
  height: 75px;
  background-color: tomato;
  position: absolute;
  border-radius: 50%;
  pointer-events:none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Follow Mouse</title>
</head>
<body>

  <div id="moveItem"></div>

</body>
</html>

相关问题