「切換檢視模式」是列表頁常見的小功能,例如電商商品列表可在網格與列表之間切換。核心概念其實很單純:用 JavaScript 換掉容器上的 class,讓不同的 CSS 規則接手排版。
<a href="#" id="switch">切換版面</a>
<div id="demo" class="showlist">
<div class="list">
<h3><a href="#">文章標題</a></h3>
<p>文章摘要</p>
</div>
...
</div>
在 #demo 中放入多個 .list,每個區塊負責顯示標題與摘要,外觀則完全交由 CSS 控制。
#demo {
width: 680px; margin: 20px auto; padding: 4px;
background: #f7f7f7; border: 1px solid #d3d3d3;
}
.list { margin: 6px; }
.list h3 { height: 26px; line-height: 26px; font-size: 14px; }
.list p { line-height: 20px; }
.showblock .list {
float: left;
width: 325px;
height: 100px;
}
#demo 負責統一外觀(背景色與邊框),而 .showblock .list 則是切換的關鍵:讓每個 .list 向左浮動並固定寬高,形成兩欄方塊排列。也就是說,showblock 這個 class 實際上是加在 #demo 上的。
$(function(){
$("#switch").toggle(function(){
$("#demo").fadeOut("fast", function(){
$(this).fadeIn("fast").addClass("showblock");
});
}, function(){
$("#demo").fadeOut("fast", function(){
$(this).fadeIn("fast").removeClass("showblock");
});
});
});
這裡用 toggle 交替執行兩段行為,並在切換前後加上 fadeOut/fadeIn,讓版面變化帶一點過渡感。真正的切換動作,就是 addClass 與 removeClass。
上述寫法有個明顯缺陷——翻頁後版面會恢復預設,使用者得重新切換一次。解法是用 cookie 或 localStorage 記錄使用者的偏好:
$(function(){
var mode = $.cookie('layoutMode');
if (mode === 'block') $("#demo").addClass("showblock");
$("#switch").toggle(function(){
$("#demo").fadeOut("fast", function(){
$(this).fadeIn("fast").addClass("showblock");
$.cookie('layoutMode', 'block', { path: '/' });
});
}, function(){
$("#demo").fadeOut("fast", function(){
$(this).fadeIn("fast").removeClass("showblock");
$.cookie('layoutMode', 'list', { path: '/' });
});
});
});
頁面載入時先讀取偏好並套用,翻頁或重新整理後版面就不會跳回預設。若不想引入外掛,用原生 localStorage.setItem 也能達到相同效果,而且沒有 4KB 容量限制。