【问题标题】:Vertical and horizontal lines that always intersect mouse cursor始终与鼠标光标相交的垂直线和水平线
【发布时间】:2020-02-28 13:39:22
【问题描述】:

我正在尝试创建两条线(一条垂直的 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>

【问题讨论】:

    标签: javascript css mouse-cursor


    【解决方案1】:

    .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>

    【讨论】:

    • 很好的答案!我没想到!酷~
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2019-11-03
    • 2022-01-21
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多