css3让div随鼠标移动而抖动起来
程序员文章站
2023-12-15 09:21:52
一些背景图片随着鼠标的移动的反向的移动,感觉跟不错,下面为大家介绍喜爱使用css3让div随鼠标移动而抖动起来,感兴趣的朋友可以参考下... 14-02-10...
最近发现一个网站,感觉用户体验不错,特别是一些背景图片随着鼠标的移动的反向的移动,感觉跟不错,于是就试着写了个小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左右偏移最多不超过的值
效果展示