用自定义CSS在图像上添加3D悬停效果?

qlzsbp2j  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(150)

当鼠标悬停在图像上时,尝试实现这种效果,这可以只用CSS实现吗?
https://mansun.co.uk/music/
先谢了!

}
.product_med img:hover {
    -webkit-transform: rotate(360deg);
    transform: rotate3d(3, 3, 1, 360deg);
    -webkit-transform-style: preserve-3d;
}
.product_med img {
    border-radius: 50%;
    transition: all 0.4s cubic-bezier(0.12,0.65,0.4,1);
    -webkit-transition: all 2.27s ease-out;
}
blmhpbnm

blmhpbnm1#

要创建这样的倾斜3D效果,您可能需要使用变换和透视。
由于在鼠标移动上倾斜无法单独使用CSS解决,请使用JavaScript:

const element = document.querySelector('.pane');
const tiltDeg = 15;

element.addEventListener('mousemove', ({
  clientX,
  clientY
}) => {
  const bcr = element.getBoundingClientRect();
  const rotX = ((clientY - bcr.top) / bcr.height * 2 - 1) * tiltDeg;
  const rotY = ((clientX - bcr.left) / bcr.width * 2 - 1) * -tiltDeg;
  element.firstElementChild.style.transform = `rotateX(${rotX}deg) rotateY(${rotY}deg)`;
});
element.addEventListener('mouseleave', () => {
  element.firstElementChild.style.transform = `rotateX(0deg) rotateY(0deg)`;
});
* {
  margin: 0;
  box-sizing: border-box;
}

.pane {
  width: 200px;
  height: 200px;
  left: 50px;
  top: 50px;
  position: relative;
  perspective: 600px;
}

.pane-tilt {
  position: relative;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  transition: 0.1s;
  display: flex;
  transform-style: preserve-3d;
}

.pane-tilt-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pane-tilt-desc {
  position: relative;
  margin: auto;
  color: #fff;
  transition: 0.3s;
  transform: translateZ(0px);
  scale: 0.6;
  opacity: 0;
}

.pane:hover .pane-tilt-desc {
  transform: translateZ(60px);
  scale: 1;
  opacity: 1;
}
<div class="pane">
  <div class="pane-tilt">
    <img class="pane-tilt-image" src="https://placekitten.com/300/287">
    <h3 class="pane-tilt-desc">Lorem ipsum</h3>
  </div>
</div>

相关问题