簡體   English   中英

如何使圖像跟隨鼠標 cursor

[英]How to make image follow mouse cursor

我已經設置了這個代碼,圖像跟隨鼠標 cursor。 但是,由於某種原因,它無法在第二個容器上正常工作。

https://codepen.io/stefanomonteiro/pen/jOarjgX

PS:無關緊要:Stackoerflow 首先強迫我 pste 代碼,而不僅僅是 codepen 鏈接。 現在它說它主要是文本。 這些公司應該減少對機器人的依賴。 有時會很煩人:)

 const items = document.querySelectorAll('.container') items.forEach((el) => { const image = el.querySelector('img') el.addEventListener('mouseenter', (e) => { gsap.to(image, { autoAlpha: 1 }) }) el.addEventListener('mouseleave', (e) => { gsap.to(image, { autoAlpha: 0 }) }) el.addEventListener('mousemove', (e) => { gsap.set(image, { x: e.pageX, y: e.pageY }) }) })
 .container { display:inline-block; background:#ff0000; width:100%; height:200px; }.container:nth-child(2){ background: #00ff00; }.container img.swipeimage { position: absolute; width: 200px; height: 200px; object-fit: cover; transform: translateX(-50%) translateY(-50%); z-index: 9; opacity: 0; visibily: hidden; pointer-events: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script> <div class="container"> <img class="swipeimage" src="https://source.unsplash.com/random"> <div class="text"> <h1>One</h1> </div> </div> <div class="container"> <img class="swipeimage" src="https://source.unsplash.com/random"> <div class="text"> <h1>Two</h1> </div> </div>

您需要將.container img.swipeimage設置為top: 0; 在您的 CSS 中,否則它將繼承其高度的一半( height + transform: translateY(-50%)

 const items = document.querySelectorAll('.container') items.forEach((el) => { const image = el.querySelector('img') el.addEventListener('mouseenter', (e) => { gsap.to(image, { autoAlpha: 1 }) }) el.addEventListener('mouseleave', (e) => { gsap.to(image, { autoAlpha: 0 }) }) el.addEventListener('mousemove', (e) => { gsap.set(image, { x: e.pageX, y: e.pageY }) }) })
 .container { display:inline-block; background:#ff0000; width:100%; height:200px; }.container:nth-child(2){ background: #00ff00; }.container img.swipeimage { position: absolute; width: 200px; top: 0; height: 200px; object-fit: cover; transform: translateX(-50%) translateY(-50%); z-index: 9; opacity: 0; visibily: hidden; pointer-events: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script> <div class="container"> <img class="swipeimage" src="https://source.unsplash.com/random"> <div class="text"> <h1>One</h1> </div> </div> <div class="container"> <img class="swipeimage" src="https://source.unsplash.com/random"> <div class="text"> <h1>Two</h1> </div> </div>

您知道先生如何使圖像上方的文字出現在 hover 上嗎? 我嘗試在 CSS 中使用 z-index 但沒有奏效,我明確將 z-index 設置為高,99 僅設置為文本但沒有奏效。

暫無
暫無

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

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