鼠標拖拽效果圖如下:
旋轉效果圖如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>炫酷旋轉</title>
<style>
* {
margin: 0px;
padding: 0;
}
.perspective {
perspective: 1000px;
perspective-origin: top;
}
#wrap {
position: relative;
width: 200px;
height: 200px;
margin: 250px auto;
transform-style: preserve-3d;
transform:rotateX(0deg) rotateY(0deg);
/* 要想實現旋轉只要把下面這段代碼去掉註釋,實現拖拽加上註釋就行 */
/* animation: rot 5s linear infinite; */
}
#wrap img {
position: absolute;
}
@keyframes rot {
0% {
transform: rotateY(0deg)
}
100% {
transform: rotateY(180deg)
}
}
</style>
</head>
<body>
<div class='perspective'>
<div id='wrap'>
<img src='./muma/1.jpg' alt='' />
<img src='./muma/2.jpg' alt='' />
<img src='./muma/3.jpg' alt='' />
<img src='./muma/4.jpg' alt='' />
<img src='./muma/1.jpg' alt='' />
<img src='./muma/2.jpg' alt='' />
<img src='./muma/3.jpg' alt='' />
<img src='./muma/4.jpg' alt='' />
<img src='./muma/1.jpg' alt='' />
<img src='./muma/2.jpg' alt='' />
<img src='./muma/3.jpg' alt='' />
<img src='./muma/4.jpg' alt='' />
</div>
</div>
</body>
<script>
var oImg = document.getElementsByTagName('img');/* 得到所有圖片 */
var oWrap = document.getElementById('wrap');
var length = oImg.length; // 列表長度
var deg = 360 / length; // 每個圖片之間間隔的角度
//頁面加載完後再執行的代碼
window.onload = function () {
//遍歷到所有的圖片ele單個元素
//.call是一個prototype,JavaScript函數內置的。.call使用它的第一個參數替換掉上面說的這個this,也就是你要傳人的數組,其它的參數就跟forEach方法的參數一樣了
//第一個參數就是傳入的圖片數組,函數參數是標籤對象,索引,和數組本身。
Array.prototype.forEach.call(oImg, function (ele, index, self) {
ele.style.transform = `rotateY(${deg * index}deg) translateZ(400px)`;
ele.style.transition = `1s ${(length - index) * .1}s`;//單個圖片出現的時間,第2個屬性延時,第一張延時最長
});
}
// 拖拽時記錄位置的變量
var newX, newY, lastX, lastY, minusX, minusX, rotX = -20, rotY = 0;
//鼠標按下事件
document.onmousedown = function (e) {
//記錄第一次的值
lastX = e.clientX;
lastY = e.clientY;
//鼠標移動事件
this.onmousemove = function (e) {
newX = e.clientX;
newY = e.clientY;
minusX = newX - lastX; // 新拖動的位置距離上一次的位置的大小
minusY = newY - lastY;
rotX -= minusY;
rotY += minusX;
oWrap.style.transform = "rotateX(" + rotX + "deg) rotateY(" + rotY + "deg)";
lastX = newX; // 更新位置
lastY = newY;
}
//鼠標鬆開事件,這是爲了讓鼠標鬆開時不在觸發移動事件
this.onmouseup = function (e) {
this.onmousemove = null;
}
}
</script>
</html>
代碼的詳細講解和思路可以參考CSS製作旋轉相冊。
js製作旋轉相冊比較方便,代碼簡單,可擴展性強,隨便加圖片不會影響代碼的執行,不用去修改代碼。有需要的友友歡迎參考,也歡迎指出不足和錯誤,一起討論,共同進步。