【问题标题】:responsive image with mouse parallax具有鼠标视差的响应图像
【发布时间】:2022-12-07 20:16:10
【问题描述】:

我已经编码了 3 层具有鼠标视差效果的图像,在全屏上图像看起来很好,但是如果我调整窗口大小,一切都会崩溃。

`


<!DOCTYPE html>

<html>
  <head>
    <link rel="stylesheet" href="css.css"/>
    <title>Document</title>
  </head>
  <body>
    <section id="main">
      <img src="canyon 3.png"  class="layer" id="c3" value="5" />
      <img src="canyon 2.png" class="layer" id="c2" value="10" />
      <h1 class="text" >bla bla bla bla bla bla bla</h1>
      <img src="canyon 1.png" class="layer" id="c1" value="20" />
    </section>
    <script src="js.js"></script>
  </body>
</html>

section{
  width: 100%;
  height:100vh;
  position: relative;
  justify-content: center;
  align-items: center;
  display: flex;
}

section img{
  position: absolute;
  width:100%;
  height:100%;
  object-fit:cover;
}


#c1{
  position: absolute;
  width:140%;
  height:max-content;
  z-index:4;
}

#c2{
  position: absolute;
  left:100px;
  width:100%;
  height:max-content;

  z-index: 2;
}

#c3{
  position: absolute;
  height:max-content;
  z-index: 1;
}

` 我真的不知道我能做些什么来让它响应。

【问题讨论】:

    标签: javascript html css parallax


    【解决方案1】:

    下面是一个示例,说明如何在 HTML 和 JavaScript 中创建具有鼠标视差的响应式图像:

    <!-- HTML code -->
    <img src="image.jpg" id="parallax-image">
    
    <!-- JavaScript code -->
    <script>
      // Get a reference to the image element
      const image = document.getElementById("parallax-image");
    
      // Add a mousemove event listener to the image
      image.addEventListener("mousemove", (event) => {
        // Get the distance from the center of the image to the mouse pointer
        const x = event.offsetX - (image.offsetWidth / 2);
        const y = event.offsetY - (image.offsetHeight / 2);
    
        // Set the image's transform property to move the image by the distance calculated above
        image.style.transform = `translate(${x * 0.01}px, ${y * 0.01}px)`;
      });
    </script>
    

    此代码使用 mousemove 事件跟踪鼠标光标在图像上的移动,然后更新图像的变换属性以将图像沿鼠标移动的方向移动少量。这会产生视差效果,其中图像似乎相对于鼠标光标移动。

    您可以通过更改平移函数中的值 0.01 来调整移动量。较高的值会产生更明显的视差效果,而较低的值会产生更微妙的效果。

    您还可以向图像添加其他样式以使其响应,例如将宽度和高度设置为 100% 并添加最大宽度值以限制图像在较大屏幕上的大小。这将确保图像在不同的屏幕尺寸和设备上正确缩放。

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      相关资源
      最近更新 更多