我正在嘗試在輪播 ( https://advertising.nytimes.com/custom-content/ ) 上實作滑鼠效果。當我將滑鼠懸停在容器上時,游標應該會改變。我讓它作業了,但它經常斷斷續續。怎樣才能順暢呢?當我添加條件陳述句時出現口吃。請幫忙。
<style>
.img {
width: 100px;
height: 100px;
object-fit: cover;
position: fixed;
top: 0;
left: 0;
}
.container {
width: 700px;
height: 900px;
background-color: orangered;
overflow: hidden;
cursor: none;
}
</style>
<div class="container">
<img
class="img"
src="https://images.unsplash.com/photo-1472457897821-70d3819a0e24?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2669&q=80"
/>
</div>
<script>
const container = document.querySelector(".container");
const img = container.querySelector(".img");
document.addEventListener("mousemove", (e) => {
if (event.target == container) {
img.style.transform = `translate3d(${e.clientX}px, ${e.clientY}px, 0)`;
}
});
</script>
uj5u.com熱心網友回復:
它就像在 旁邊添加一個邏輯或一樣簡單event.target == container。它的移動很奇怪,因為當你的滑鼠滑過影像時,它就不再是目標了。
為了解決這個問題,我們需要為影像添加一個 ID,以便我們可以在我們的event.target. 所以<img>看起來像這樣
<img id"img" src="https://images.unsplash.com/photo-147245789782170d3819a0e24ixlib=rb4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2669&q=80"/>
設定 id 后,我們可以添加邏輯 OR 陳述句,它看起來像這樣
event.target == container || picture
希望我能幫上忙!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537830.html
