黑松山资源网 Design By www.paidiu.com
最近发现一个网站,感觉用户体验不错,特别是一些背景图片随着鼠标的移动的反向的移动,感觉跟不错,于是就试着写了个小demo模仿一下

复制代码代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.layer {
width:400px;
height:400px;
background-color:#FF7373;
transa
}
.A {
position: absolute;
top: 23px;
left: 10px;
}
.B {
position: absolute;
top: 223px;
left: 516px;
}
.C {
position: absolute;
top: 384px;
left: 1000px;
}
</style>
</head>
<body>
<div class="layer A"></div>
<div class="layer B"></div>
<div class="layer C"></div>
</body>
<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>
</html>

说明一下分别拿到每个div的长度和宽度,通过比例算出相对于窗口的合适的偏移量,max是每个div左右偏移最多不超过的值

效果展示
css3让div随鼠标移动而抖动起来
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com