如何使用HTML、CSS和JavaScript创建视差效果?


在本文中,我们将学习视差效果以及如何使用HTMLCSSJavaScript创建它们。我们将使用鼠标移动事件来显示视差效果。在视差效果期间,两张不同的图像会并排移动。两张图像将并行工作并进行相同的转换。唯一的区别在于它们朝相反的方向移动。

视差效果用于改善网站的用户体验并增强网站的交互性。我们可以以不同的速度和不同的方向移动前景和背景图像。视差效果可以有多种组合,例如移动文本和图像或图像和图像。

示例

在下面的示例中,我们使用两张图像实现了视差效果。两张图像以相同的速度朝相反的方向移动。

#文件名: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <style>
   * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: sans-serif;
   }
   body {
      background-color: lightgrey;
   }
   .mouse_move {
      position: relative;
      width: 100%;
      height: 100vh;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
   }
   .mouse_move h2 {
      position: relative;
      font-size: 40px;
      color: black;
   }
   .mouse_move img {
      position: absolute;
   }
   #img1 {
      top: 80px;
      left: 80px;
      height: 250px;
      width: 250px;
   }
   #img2 {
      bottom: 80px;
      right: 80px;
      height: 250px;
      width: 250px;
   }
   </style>
   <title>Parallax Effect</title>
</head>
<body>
   <div class="mouse_move">
   <img
      id="img1"
   src="https://tutorialspoint.com/assets/questions/media/64678/5.png"
   class="mouse"
   value="7"/>
   <h2>Welcome To Tutorials Point</h2>
   <img
      id="img2" src="https://tutorialspoint.com/images/logo.png" class="mouse" value="-7"/>
   </div>
   <script type="text/javascript">
   document.addEventListener("mousemove", parallax);
   function parallax(event) {
      this.querySelectorAll(".mouse").forEach((shift) => {
         const position = shift.getAttribute("value");
         const x = (window.innerWidth - event.pageX * position) / 90;
         const y = (window.innerHeight - event.pageY * position) / 90;
         shift.style.transform = `translateX(${x}px) translateY(${y}px)`;
      });
   }
   </script>
</body>
</html>

输出

更新于:2022年4月26日

1K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.