如何使用HTML CSS和Javascript创建mousemove视差效果

如何使用HTML CSS和Javascript创建mousemove视差效果

在本文中,我们将学习如何使用CSS和JavaScript创建mousemove视差效果。在mousemove视差效果中,当我们移动鼠标时,图像会以不同的速度在不同的方向上移动。视差效果用于使网站更具吸引力,并增加网站的互动性。视差效果是以不同的速度和不同的方向滚动或移动前景和背景图像的一种方式。我们可以使用文本与图像的组合或图像与图像的组合来创建视差效果。

方法:

  • <body>标签中,创建<div>标签来分配一些应用视差效果的图像,并为每个图像分配一个类名和值属性,用于控制图像的移动量。
  • 对于CSS样式,可以在style标签中添加一些CSS属性,如图像的位置和大小。
  • 我们使用JavaScript来实现视差效果。在给出的script标签下面的代码段中,我们创建了一个名为parallax的函数,它使用img标签的类名来获取定位和移动图像的值。

示例: 在这一步中,我们将使用上述方法创建一个movemouse视差效果。

HTML

<!-- Filename:index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: sans-serif;
        }
 
        body {
            background-color: rgb(102, 189, 16);
        }
 
        .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: 100px;
            color: white;
        }
 
        .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</title>
</head>
 
<body>
    <div class="mouse_move">
        <img id="img1" src=
"https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo.png"
            class="mouse"
            value="5" />
        <h2>GeeksforGeeks</h2>
        <img id="img2" src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"
            class="mouse" value="-5" />
    </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>
JavaScript

输出:

如何使用HTML CSS和Javascript创建mousemove视差效果

从以上示例可见,当我们将鼠标光标从一个方向移动到另一个方向时,图像开始浮动或移动。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册