如何使图像跟随鼠标光标

How to make image follow mouse cursor

我已经设置了这段代码,其中图像跟随鼠标光标。但是,由于某种原因,它在第二个容器上无法正常工作。

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

PS:无关紧要:Stackoerflow 首先迫使我 pste 代码,而不仅仅是 codepen link。现在它说它主要是文本。这些公司应该减少对机器人的依赖。有时会很烦人 :)

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>

你需要在你的CSS中将.container img.swipeimage设置为top: 0;,否则它会继承它一半的高度(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>