簡體   English   中英

始終與鼠標相交的垂直線和水平線 cursor

[英]Vertical and horizontal lines that always intersect mouse cursor

我正在嘗試創建始終跟隨鼠標 cursor 並相互感興趣的兩條線(一條垂直的 100 VH 和 1 px 寬度和一條水平線 100vw 和 1 px 高度)。 我的代碼有兩個問題:1)我不知道我必須在垂直線上分配什么高度值(水平線很容易,我將它設置為 200 vw 和 body overflow-x hidden 所以沒關系) 和 2) 當我向下滾動時,直到我不移動鼠標,水平線保持在同一個 position 上,它僅在我更改鼠標 Z4757FE07FD492A8BEEZEA6A760D683D6 后才跟隨 cursor。 這是我的代碼:

 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 ,因為它們是相對於客戶區,而不是整個頁面。

不要移動需要溢出的整個 cursor,而是水平移動.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>

您可以通過使用如下scroll事件來實現您的目標。

 let yValue = 0; let xValue = 0; const cursor = document.querySelector('.cursor'); document.addEventListener('mousemove', e => { yValue = e.pageY - window.scrollY; xValue = e.pageX; cursor.setAttribute("style", "top: "+(e.pageY)+"px; left: "+(e.pageX)+"px;") }) document.addEventListener('scroll', e => { cursor.setAttribute("style", "top: "+(window.scrollY + yValue)+"px; left: "+(xValue)+"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; transition: all 0.1s linear; }.hl { position: absolute; left:-100vw; height: 1px; width: 200vw; background: black; transition: all 0.1s linear; }
 <div class="cursor"> <div class="cursor-lines"> <div class="vt"></div> <div class="hl"></div> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM