2

我正在尝试创建两条线(一条垂直的 100 VH 和 1 px 的宽度,一条水平的 100vw 和 1 px 的高度),它们始终跟随鼠标光标并相互感兴趣。我的代码有两个问题:1)我不知道我必须在垂直线上分配什么高度值(水平线很容易,我将它设置为 200 vw 和 body overflow-x hidden 所以没关系) 和 2) 当我向下滚动时,直到我不移动鼠标,水平线保持在同一位置,只有在我更改鼠标位置后它才会跟随光标。这是我的代码:

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: " + (e.pageY) + "px; left: " + (e.pageX) + "px;")
})
body {
  overflow-x: hidden;
  height: 5000px;
}

.cursor {
  position: absolute;
}

.cursor-lines {
  position: relative;
}

.vt {
  position: absolute;
  height: 200vh;
  top: -100vh;
  width: 1px;
  background: black;
}

.hl {
  position: absolute;
  left: -100vw;
  height: 1px;
  width: 200vw;
  background: black;
}
<div class="cursor">
  <div class="cursor-lines">
    <div class="vt"></div>
    <div class="hl"></div>
  </div>
</div>

4

1 回答 1

6

The .cursor should be a fixed area, and you should use clientX and clientY, since they are relative to the client area, and not the entire page.

Instead of moving the entire cursor, which requires an overflow, move the .vt line horizontally, and the .hl line vertically.

const cursorVT = document.querySelector('.vt')
const cursorHL = document.querySelector('.hl')

document.addEventListener('mousemove', e => {
  cursorVT.setAttribute('style', `left: ${e.clientX}px;`)
  cursorHL.setAttribute('style', `top: ${e.clientY}px;`)
})
body {
  height: 500vh;
  margin: 0;
  overflow: auto;
}

.cursor {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  pointer-events: none;
}

.vt {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 1px;
  background: black;
}

.hl {
  position: absolute;
  height: 1px;
  left: 0;
  right: 0;
  background: black;
}
<div class="cursor">
  <div class="vt"></div>
  <div class="hl"></div>
</div>

于 2019-11-02T17:03:13.067 回答