3DX20视差效果

xiaoxiao2021-02-28  115

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .avatar { width: 300px; height: 300px; margin: 50px auto; background: url('images/dog2.jpg')center no-repeat; background-size: contain; transition: all .3s linear; transform-origin: 50%; border-radius: 5px; } </style> </head> <body> <div class="avatar"></div> <script> window.onload=function () { let el = document.querySelector('.avatar') el.addEventListener('mousemove', (e) => { // 获取元素到页面的left/top/width/height let thisPX = el.getBoundingClientRect().left let thisPY = el.getBoundingClientRect().top let boxWidth = el.getBoundingClientRect().width let boxHeight = el.getBoundingClientRect().height let mouseX = e.pageX - thisPX let scrollTop = document.documentElement.scrollTop + document.body.scrollTop //计算滚动高度 let mouseY = e.pageY - scrollTop - thisPY; //减去滚动高度 let X let Y X = mouseX - boxWidth / 2 Y = boxHeight / 2 - mouseY el.style.transform = `perspective(300px) rotateY(${X / 10}deg) rotateX(${Y / 10}deg)` el.style.boxShadow = `${-X / 20}px ${Y / 20}px 50px rgba(0, 0, 0, 0.3)` }) el.addEventListener('mouseleave', () => { el.style.transform = `perspective(300px) rotateY(0deg) rotateX(0deg)` el.style.boxShadow = '' }) } </script> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-35146.html

最新回复(0)