3×3 九宮格佈局,點擊頂部導航觸發面板平滑滑動到對應位置,支持水平、垂直、對角線多方向過渡。
<ul id="head">
<li id="l_01">面板1</li> <li id="l_02">面板2</li> <li id="l_03">面板3</li>
<li id="l_04">面板4</li> <li id="l_05">面板5</li> <li id="l_06">面板6</li>
<li id="l_07">面板7</li> <li id="l_08">面板8</li> <li id="l_09">面板9</li>
</ul>
<div id="box">
<div id="bg">
<div id="class_1" class="cell">內容1</div>
<div id="class_2" class="cell">內容2</div>
<div id="class_3" class="cell">內容3</div>
<div id="class_4" class="cell">內容4</div>
<div id="class_5" class="cell">內容5</div>
<div id="class_6" class="cell">內容6</div>
<div id="class_7" class="cell">內容7</div>
<div id="class_8" class="cell">內容8</div>
<div id="class_9" class="cell">內容9</div>
</div>
</div>
#head { position:fixed; top:0; left:0; width:100%; height:30px; background:#0088ff; z-index:10; }
#head li { float:left; height:30px; padding:0 15px; line-height:30px; cursor:pointer; color:#fff; font-size:14px; }
#head li:hover { background:#0055ff; border-bottom:10px solid #0011ff; }
#box { position:absolute; top:0; left:0; width:100%; height:100%; overflow:hidden; }
#bg { position:absolute; top:0; left:0; width:300%; height:300%; } /* 3x3 網格總寬高 */
.cell { width:33.33%; height:33.33%; float:left; box-sizing:border-box; }
/* 九宮格定位 */
#class_1 { left:0%; top:0%; } #class_2 { left:100%; top:0%; } #class_3 { left:200%; top:0%; }
#class_4 { left:0%; top:100%; } #class_5 { left:100%; top:100%; } #class_6 { left:200%; top:100%; }
#class_7 { left:0%; top:200%; } #class_8 { left:100%; top:200%; } #class_9 { left:200%; top:200%; }
核心:#bg 寬高為視口 3 倍,九個 .cell 浮動排列成 3×3 網格,通過移動 #bg 的 top/left 實現視口切換。
$(function() {
var $bg = $('#bg');
var positions = {
l_01: {top:0, left:0}, l_02: {top:0, left:-100}, l_03: {top:0, left:-200},
l_04: {top:-100, left:0}, l_05: {top:-100, left:-100}, l_06: {top:-100, left:-200},
l_07: {top:-200, left:0}, l_08: {top:-200, left:-100}, l_09: {top:-200, left:-200}
};
$('#head li').click(function() {
var id = this.id;
if (positions[id]) {
$bg.stop(true, true).animate({top: positions[id].top + '%', left: positions[id].left + '%'}, 'slow');
}
});
});
vw/vh 替代百分比,@media 調整網格列數(手機變單列)。hammer.js 或原生 touch 事件實現手指滑動切換。data-src)。history.pushState 更新 URL,支持瀏覽器前進後退。#bg {
display: grid; grid-template-columns: repeat(3, 100vw); grid-template-rows: repeat(3, 100vh);
width: 300vw; height: 300vh;
scroll-snap-type: both mandatory; /* 雙向吸附 */
overflow: hidden; /* 由容器控制滾動 */
}
.cell { scroll-snap-align: start; }
配合 scrollTo({top, left, behavior:'smooth'}) 可完全用 CSS 控制吸附與動畫,JS 僅負責計算目標座標。
九宮格滑動通過「超大容器 + 絕對定位子元素 + animate 移動容器」實現,邏輯清晰且易於擴展。現代項目可考慮 CSS Scroll Snap + JS 路由同步,減少 JS 動畫計算,提升性能與流暢度。