先看效果图
原理rotate的使用
当鼠标放到图片的一角处的时候,实现该处向下坍缩的效果,即用的是rotate的3D属性,此时的图片向相应的方向的进行偏转,偏转的角度x,y如下图所示:(与rotateZ无关)
需要注意的是偏转的x,y的正负值。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
section {
margin: auto;
width: 500px;
height: 250px;
margin-top: 100px;
}
.cover {
width: 100%;
height: 100%;
border-radius: 10px;
background-color: #5e5e5e;
}
/*transform*/
section {
position: relative;
perspective: 1000px;
}
.cover {
transform-origin: 50% 50% 0;
transition: all .2s;
}
</style>
</head>
<body>
<section>
<div class="cover"></div>
</section>
<script>
var origin = {
X: document.body.clientWidth / 2,//可见区域宽度的一半
Y: document.body.clientHeight / 2//可见区域高度的一半
};
var o = document.querySelector('.cover');
document.querySelector('section').onmouseover = function() {
document.querySelector('section').addEventListener('mousemove', function(e) {
// chrome:
// e.pageX——相对整个页面的坐标
// e.layerX——相对当前坐标系的border左上角开始的坐标
// e.offsetX——相对当前坐标系的border左上角开始的坐标
// e.clientX——相对可视区域的坐标
// e.x——相对可视区域的坐标
var rotate = {
x: 1 - e.pageY / origin.Y,//rotateX的偏转角度
y: e.pageX / origin.X - 1 //rotateY的偏转角度
};
var transform = "rotateX(" + rotate.x * 10 + "deg) rotateY(" + rotate.y * 10 + "deg)"; //变换效果
o.style.transform = transform;
o.style.boxShadow = -parseInt(rotate.y * 30) + 'px ' + parseInt(rotate.x * 20 + 20) + 'px ' + '50px #333'; //边框阴影效果
});
};
document.querySelector('section').onmouseout = function() {
o.style.transform = "rotateX(0deg) rotateY(0deg)";
o.style.boxShadow = '0px 0px';
}
</script>
</body>
</html>`
如果有朋友对css 3d 属性不是很熟悉的,推荐一篇博客:css3-3d-transform-perspective-张鑫旭