南强小屋 Design By 杰米
最近发现一个网站,感觉用户体验不错,特别是一些背景图片随着鼠标的移动的反向的移动,感觉跟不错,于是就试着写了个小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左右偏移最多不超过的值
效果展示
复制代码代码如下:
<!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,随鼠标移动
南强小屋 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
南强小屋 Design By 杰米
暂无css3让div随鼠标移动而抖动起来的评论...