近大遠(yuǎn)小.gif
前置知識(shí):CSS position言询,js map函數(shù)
實(shí)現(xiàn)原理:
視覺原理:遠(yuǎn)處的物體移動(dòng)慢俯萎,近處的物體移動(dòng)快
實(shí)現(xiàn)原理:在鼠標(biāo)移動(dòng)的時(shí)候,在原 div 的原有位置上+鼠標(biāo)移動(dòng)的距離和z-index的乘積
Q:為什么要乘z-index?
A:在初始div的時(shí)候要給每個(gè)都設(shè)置z-index运杭,越大(離你越近)的物體z-index越高or大
步驟:
①獲取每個(gè)div
②獲取每個(gè)div當(dāng)前的left和top
③鼠標(biāo)移動(dòng)時(shí)給每個(gè)元素加上鼠標(biāo)移動(dòng)距離*z-index夫啊;
代碼實(shí)現(xiàn):
〇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>
①獲取每個(gè)div:
let aDiv=document.getElementsByTagName('div');
②獲取每個(gè)div當(dāng)前的left和top:
let oldPos=Array.from(aDiv).map(div=>{
return {
left:div.offsetLeft,
top:div.offsetTop
}
});
③鼠標(biāo)移動(dòng)時(shí)給每個(gè)元素加上鼠標(biāo)移動(dòng)距離*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移動(dòng)的不要太快
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>