javascript - 始终与鼠标光标相交的垂直线和水平线

标签 javascript css mouse-cursor

我正在尝试创建两条线(1 条垂直线,100 VH 和 1 px 宽,1 条水平线,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>

最佳答案

.cursor应该是一个固定的区域,你应该使用clientXclientY,因为它们是相对于客户区的,而不是整个页面。

不是移动整个光标,这需要溢出,而是水平移动 .vt 行,垂直移动 .hl 行。

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>

关于javascript - 始终与鼠标光标相交的垂直线和水平线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58673089/

相关文章:

javascript - event.currentTarget.value 返回未定义的 javascript

javascript - 在 JavaScript 中创建的元素添加 .type 和 .disabled 属性,但不添加 .form 或 .value

css - 在 Canvas HTML5 中分层文本和图像

css - 默认 CSS 接管我的代码的问题

html - 为什么 CSS 光标属性不适用于自定义 URL?

macos - 如何将光标锁定在 Mac OS X 上的窗口内部?

c# - 在 C# 中将鼠标光标移出屏幕

javascript - NodeJS 检测修改过的文件

javascript - 如何在 React JS 中处理 JSX 内的 Promise?

javascript - 动态选择最后一个子元素