最近在公司接到一個需求,里面有一個三級跳轉。類似於選擇地址的時候,選擇的順序是:省份->市->區。如果分三個頁面跳轉,那么體驗非常不好,如果引入其他框架做成單頁應用,又比較麻煩。所以可以用js把這一塊做成單頁應用的樣子。。。
主要思路
通過改變url的hash值,跳到相應模塊。先把默認模塊顯示出來,其他模塊隱藏,分別給三個模塊定義三個hash值,點擊默認模塊的選項的時候,改變hash值,同時在window上監聽hashchange事件,並作相應模塊跳轉邏輯處理。這樣即可模擬瀏覽器的前進后退,而且用戶體驗也比較好。
下面詳細來看看,現在有一個場景,選擇順序是:車牌子->車型->車系。
首先HTML部分。默認顯示車牌子選擇列表,其他兩個模塊隱藏。
<div class="wrap">
<div id="Brand">
<div>品牌</div>
<ul class="mycar_hot_list">
<li>
<p>大眾</p>
</li>
</ul>
</div>
<div id="Type" style="display:none">
<dl>
<dt>比亞迪汽車</dt>
<dd>宋</dd>
</dl>
</div>
<div id="Series" style="display:none">
<ul class="mycar_datalist">
<li>
2013年款
<li>
</ul>
</div>
</div>
js邏輯控制部分
①定義一個變量對象,存儲三個模塊中分別選擇的數據、定義hash值、相應模塊的處理邏輯函數。
info={
brand:'',
carType:'',
carSeries:'',
pages:['Brand','Type','Series']
};
info.selectBrand=function(){
document.title = '選擇商標';
brandEvent();
}
//選擇車型
info.selectType=function(){
document.title = '選擇車型';
document.body.scrollTop = 0; //滾到頂部
window.scrollTo(0, 0);
typeEvent(); //為該模塊的dom綁定事件或做其他邏輯
}
//選擇車系
info.selectSeries=function(){
document.title = '選擇車系';
document.body.scrollTop = 0;
window.scrollTo(0, 0);
seriesEvent();
}
②dom綁定事件&其他邏輯
function brandEvent(){
//綁定跳轉
$('#Brand ul li').click(function(){
info.brand=$(this).find('p').text();
goPage('Type');
})
}
function typeEvent(){
//綁定跳轉
$('#Type dd').click(function(){
info.carType=$(this).text();
goPage('Series');
})
}
function seriesEvent(){...}
③goPage邏輯跳轉控制
function goPage(tag) {
if ((tag == 'Brand')&&(location.hash.indexOf('Type')!=-1)){ // 后退操作
history.back();
document.title = '選擇商標';
}else if ((tag == 'Type')&&(location.hash.indexOf('Series')!=-1)){
history.back();
document.title = '選擇車型';
}else {
location.hash = tag;
}
}
④js入口文件(這里用了zepto.js來選擇dom)
window.onload=function(){
info.selectBrand(); //為默認顯示的模塊中的元素綁定相應的事件及其他邏輯
$(window).on("hashchange", function (e) {
doHashChange();
});
}
⑤最重要的hash改變邏輯控制
function doHashChange(){
//獲取hash的值
var hash = location.hash.split('|')[0],
tag = hash.replace(/#/g, '');
if (info.pages.indexOf(tag) == -1) {
tag = 'Brand';
}
$('.wrap').children('div').hide();
//執行每個模塊不同的方法
if(typeof(info['select' + tag]) == "function"){
info['select' + tag]();
}
//展示對應dom
$('#' + tag).show();
}
想參考demo?
本例沒有demo。。。^_^
