悬停时 CSS 旋转框,光标下方有灯光

问题描述 投票:0回答:1

我有以下 html 文件:

const container = document.querySelector('.container');
const box = document.querySelector('.box');
const light = document.querySelector('.light');

container.addEventListener('mousemove', moveLight);

function moveLight(event) {
  const containerRect = container.getBoundingClientRect();
  light.style.left = event.clientX - containerRect.left + 'px';
  light.style.top = event.clientY - containerRect.top + 'px';
}

// Adjust the light position initially in case of default hover
container.addEventListener('mouseenter', moveLight);

container.addEventListener('mousemove', rotateBox);

function rotateBox(event) {
  const containerRect = container.getBoundingClientRect();
  const centerX = containerRect.left + containerRect.width / 2;
  const centerY = containerRect.top + containerRect.height / 2;
  const mouseX = event.clientX;
  const mouseY = event.clientY;

  const deltaX = mouseX - centerX;
  const deltaY = mouseY - centerY;

  const maxRotation = 30; // Adjust the maximum rotation angle
  const rotateX = -deltaY / centerY * maxRotation; // Negative rotation for bringing closer
  const rotateY = -deltaX / centerX * maxRotation; // Negative rotation for bringing closer

  box.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
}
body {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.container {
  position: relative;
  width: 600px;
  height: 400px;
  perspective: 800px;
  /* Adjust as needed */
  overflow: hidden;
}

.box {
  width: 100%;
  height: 100%;
  background-color: #0d419d;
  transition: transform 0.3s ease;
  position: relative;
  overflow: hidden;
}

.light {
  position: absolute;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background-color: #006d32;
  /* Adjust opacity as needed */
  pointer-events: none;
  /* Ensure the light doesn't interfere with mouse events */
  transform: translate(-50%, -50%);
  display: none;
  /* Initially hidden */
  z-index: 1;
  filter: blur(3rem);
}

.container:hover .light {
  display: block;
  /* Show the light when hovering over the container */
}
<div class="container">
  <div class="box"></div>
  <div class="light"></div>
</div>

这表现出了一些我不知道如何修复的行为。它正在旋转,但只有盒子的一部分在悬停时旋转,而其余部分则不旋转,从而改变了 2d 盒子的形状。

我希望整个盒子朝用户旋转(所以我假设 -z 方向),所以如果我将鼠标悬停在左上角,左上角会向我移动一点,盒子的其余部分表现正常(作为一件)。

我确信这可以在纯CSS中完成,如果有人有这个解决方案,我更喜欢它,比如带有以下内容的转换属性?

perspective(700px) rotateX(-0.03deg) rotateY(0.03deg);
javascript html css
1个回答
0
投票

我看到的问题是,当 .box 旋转时,它到达了父元素(.container)的边界,并且 .container 切断了 .box 超出其边界的整个可见部分,因为这正是如何“溢出:隐藏”有效。

您的代码对我来说非常完美,这个小调整将帮助您看到它:从“.container”元素中删除“

overflow: hidden;
”属性。

所以让它保持这样的风格:

.container {
    position: relative;
    width: 600px;
    height: 400px;
    perspective: 800px;
}
© www.soinside.com 2019 - 2024. All rights reserved.