简单的鼠标移动元素近大远小效果

6次阅读

共计 2274 个字符,预计需要花费 6 分钟才能阅读完成。

效果:

前置知识:CSS position,js map 函数

实现原理:

视觉原理:远处的物体移动慢,近处的物体移动快
实现原理:在鼠标移动的时候,在原 div 的原有位置上 + 鼠标移动的距离和 z -index 的乘积

*Q: 为什么要乘 z -index?
A: 在初始 div 的时候要给每个都设置 z -index,越大(离你越近)的物体 z -index 越高 or 大 *

步骤:

①获取每个 div
②获取每个 div 当前的 left 和 top
③鼠标移动时给每个元素加上鼠标移动距离 *z-index;

代码实现:

HTML 代码:

<div style="width:50px;height:50px;left:210px;top:50px;position: absolute;z-index: 1;background: blueviolet"></div>
<div style="width:100px;height:100px;left:50px;top:130px;position: absolute;z-index: 2;background: rgb(223, 66, 139)"></div>
<div style="width:150px;height:150px;left:300px;top:150px;position: absolute;z-index: 3;background: rgb(65, 163, 139)"></div>
<div style="width:200px;height:200px;left:50px;top:400px;position: absolute;z-index: 4;background: rgb(226, 197, 35)"></div>

①获取每个 div:

 let aDiv=document.getElementsByTagName('div');

②获取每个 div 当前的 left 和 top:

let oldPos=Array.from(aDiv).map(div=>{
                return {
                    left:div.offsetLeft,
                    top:div.offsetTop
                }
            });

③鼠标移动时给每个元素加上鼠标移动距离 *z-index;

document.onmousemove=function(ev){
                let event=ev||window.event;
                Array.from(aDiv).forEach((div,index)=>{div.style.left=oldPos[index].left+event.clientX*div.style.zIndex/100+'px'; // 除 100 是为了 div 移动的不要太快
                    div.style.top=oldPos[index].top+event.clientY*div.style.zIndex/100+'px';// 同理
                })
            }

完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        window.onload=function(){let aDiv=document.getElementsByTagName('div');
            let oldPos=Array.from(aDiv).map(div=>{
                return {
                    left:div.offsetLeft,
                    top:div.offsetTop
                }
            });

            document.onmousemove=function(ev){
                let event=ev||window.event;
                Array.from(aDiv).forEach((div,index)=>{div.style.left=oldPos[index].left+event.clientX*div.style.zIndex/100+'px';                   
                    div.style.top=oldPos[index].top+event.clientY*div.style.zIndex/100+'px';
                })
            }
        }
    </script>
</head>
<body>
    <div style="width:50px;height:50px;left:210px;top:50px;position: absolute;z-index: 1;background: blueviolet"></div>
    <div style="width:100px;height:100px;left:50px;top:130px;position: absolute;z-index: 2;background: rgb(223, 66, 139)"></div>
    <div style="width:150px;height:150px;left:300px;top:150px;position: absolute;z-index: 3;background: rgb(65, 163, 139)"></div>
    <div style="width:200px;height:200px;left:50px;top:400px;position: absolute;z-index: 4;background: rgb(226, 197, 35)"></div>
</body>
</html>

正文完
 0