我试图创建两条线(始终垂直于鼠标光标并彼此感兴趣)(垂直方向为100 VH,宽度为1 px,垂直方向为1水平,宽度为100vw,高度为1 px)。我的代码有两个问题:1)我不知道必须在垂直线上分配什么高度值(水平很容易,我将其设置为200 vw,而身体溢出-x处于隐藏状态,这样就可以了)和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>
答案 0 :(得分:2)
.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>