<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>图片3D旋转效果</title> <style type="text/css"> .box-3d { margin: 20vh auto 0; width: 170px; height: 170px; perspective: 1000px; } .box-3d-content { width: 170px; height: 170px; position: relative; transform-origin: 50%; transform: translateZ(-85px) rotateY(0deg) rotateX(0deg); transition: transform 0.5s linear; transform-style: preserve-3d; } .box-3d-content img { width: 100%; height: 100%; background-color: #efeff2; position: absolute; left: 0; top: 0; } .box-3d-content img:nth-child(1) { transform: translateZ(84px); } .box-3d-content img:nth-child(2) { transform: rotateY(90deg) translateZ(84px); } .box-3d-content img:nth-child(3) { transform: rotateY(-90deg) translateZ(84px); } .box-3d-content img:nth-child(4) { transform: rotateX(-90deg) translateZ(84px); } .box-3d-content img:nth-child(5) { transform: rotateX(90deg) translateZ(84px); } </style> </head> <body> <div class="box-3d"> <div class="box-3d-content"> <img src="http://img.momen.vip/xsfm.jpg"> <img src="http://img.momen.vip/xsfm.jpg"> <img src="http://img.momen.vip/xsfm.jpg"> <img src="http://img.momen.vip/xsfm.jpg"> <img src="http://img.momen.vip/xsfm.jpg"> </div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> <script type="text/javascript"> //图片3D旋转效果 $(".box-3d").on("mouseenter mouseleave", function(e) { spin(e, this); }); //获取滚动条高度 function getScrollTop() { var scrollTop = 0; if (document.documentElement && document.documentElement.scrollTop) { scrollTop = document.documentElement.scrollTop; } else if (document.body) { scrollTop = document.body.scrollTop; } return scrollTop; } function spin(e, obj) { var sTop = getScrollTop(); var w = obj.offsetWidth; var h = obj.offsetHeight; var x = e.pageX - obj.getBoundingClientRect().left - w / 2; var y = e.pageY - obj.getBoundingClientRect().top - sTop - h / 2; var direction = Math.round((((Math.atan2(y, x) * 180 / Math.PI) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左” var eventType = e.type; var box3D = $(obj).find(".box-3d-content"); if (eventType == 'mouseenter') { switch (direction) { case 0: box3D.css("transform", "translateZ(-85px) rotateY(0deg) rotateX(-90deg)"); break; case 1: box3D.css("transform", "translateZ(-85px) rotateY(-90deg) rotateX(0deg)"); break; case 2: box3D.css("transform", "translateZ(-85px) rotateY(0deg) rotateX(90deg)"); break; case 3: box3D.css("transform", "translateZ(-85px) rotateY(90deg) rotateX(0deg)"); break; } } else { box3D.css("transform", "translateZ(-85px) rotateY(0deg) rotateX(0deg)"); } } </script> </body> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » 图片3D旋转效果 喜欢 (1)or分享 (0)