最近发现一个网站,感觉用户体验不错,特别是一些背景图片随着鼠标的移动的反向的移动,感觉跟不错,于是就试着写了个小demo模仿一下
http://www.kennedyandoswald.com/#!/failure-intro-a-poem
html> Insert title here <script type="text/javascript"> var items = document.getElementsByClassName("layer"); document.addEventListener('mousemove', function (evt){ var x = evt.clientX; var y = evt.clientY; //console.log(x); var winWidth = window.innerWidth; var winHeight = window.innerHeight; var halfWidth = winWidth / 2; var halfHeight = winHeight / 2; var rx = x - halfWidth; var ry = halfHeight - y; var length = items.length; var max = 30; for (var i = 0 ; i < length ; i++) { var dx = (items[i].getBoundingClientRect().width/max)*(rx / -halfWidth); var dy = (items[i].getBoundingClientRect().height/max)*(ry / halfHeight); items[i].style['transform'] = items[i].style['-webkit-transform'] = 'translate('+dx+'px,'+dy+'px)'; } }, false); </script>
说明一下分别拿到每个div的长度和宽度,通过比例算出相对于窗口的合适的偏移量,max是每个div左右偏移最多不超过的值
效果展示