通過鼠標懸浮實現讓元素在九宮格內移動,最終回到原點。
在本案例中使用了過渡
+定位
+opacity
三個主要的知識點。
當鼠標懸浮在九宮格之上的時候,就讓元素進行位置切換,但是僅僅通過定位的移動並不能一次性進行多個方向的位移,所以采用了過渡延遲
+元素隱藏
這樣的一個小技巧,從而實現在視覺上的一個欺騙。
下面是代碼分享:
<!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>跳轉九宮格</title>
<style>
* {
margin:0;
padding:0;
}
.box {
width: 600px;
height: 600px;
border-top: 1px solid red;
border-left:1px solid red;
/* margin:40px auto; */
position: relative;
box-sizing: border-box;
display: inline-block;
}
/* 設置九宮格 */
.box .table div {
box-sizing: border-box;
display: inline-block;
width: 196px;
height: 200px;
border-right: 1px solid red;
border-bottom: 1px solid red;
}
/* 設置移動的元素 */
.box .d1 {
box-sizing: border-box;
position: absolute;
width: 196px;
height: 200px;
background-color: orange;
top: 0;
left: 0;
transition: top 1s,left 1s 1s,opacity 1ms 2s;
}
.box:hover .d1 {
top: 200px;
left: 200px;
opacity: 0;
}
/* 第二個盒子 */
.box .d2 {
box-sizing: border-box;
position: absolute;
width: 196px;
height: 200px;
background-color: orange;
top: 200px;
left: 200px;
/* 第一個盒子延遲1s 共用時兩秒 所以第二個盒子應該在位移的屬性上分別加上1s相對於上一個盒子 */
transition: top 1s 2s,left 1s 3s,visibility 1s 2s,opacity 1ms 4s;
visibility: hidden;
}
.box:hover .d2 {
visibility: visible;
top:0;
left: 400px;
opacity: 0;
}
.box .d3 {
box-sizing: border-box;
position: absolute;
width: 196px;
height: 200px;
background-color: orange;
top: 0;
left: 400px;
visibility: hidden;
transition: top 1s 4s,left 1s 5s,visibility 1s 4s,opacity 1ms 6s;
}
.box:hover .d3 {
visibility: visible;
top: 408px;
left: 0;
opacity: 0;
}
.d4 {
box-sizing: border-box;
position: absolute;
width: 196px;
height: 200px;
background-color: orange;
top: 408px;
visibility: hidden;
transition: top 1s 6s,visibility 1ms 6s,opacity 1s 7s;
}
.box:hover .d4 {
visibility: visible;
top: 0;
opacity: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="content">
<div class="d1"></div>
<div class="d2"></div>
<div class="d3"></div>
<div class="d4"></div>
</div>
<div class="table">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
</body>
</html>
效果如下: