我正在尝试创建两条线(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
应该是一个固定的区域,你应该使用clientX
和clientY
,因为它们是相对于客户区的,而不是整个页面。
不是移动整个光标,这需要溢出,而是水平移动 .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/