最近在公司接到一個(gè)需求,里面有一個(gè)三級(jí)跳轉(zhuǎn)。類似于選擇地址的時(shí)候,選擇的順序是:省份->市->區(qū)。如果分三個(gè)頁面跳轉(zhuǎn),那么體驗(yàn)非常不好,如果引入其他框架做成單頁應(yīng)用,又比較麻煩。所以可以用js把這一塊做成單頁應(yīng)用的樣子。。。
主要思路
通過改變url的hash值,跳到相應(yīng)模塊。先把默認(rèn)模塊顯示出來,其他模塊隱藏,分別給三個(gè)模塊定義三個(gè)hash值,點(diǎn)擊默認(rèn)模塊的選項(xiàng)的時(shí)候,改變hash值,同時(shí)在window上監(jiān)聽hashchange事件,并作相應(yīng)模塊跳轉(zhuǎn)邏輯處理。這樣即可模擬瀏覽器的前進(jìn)后退,而且用戶體驗(yàn)也比較好。
下面詳細(xì)來看看,現(xiàn)在有一個(gè)場(chǎng)景,選擇順序是:車牌子->車型->車系。
首先HTML部分。默認(rèn)顯示車牌子選擇列表,其他兩個(gè)模塊隱藏。
<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邏輯控制部分
①定義一個(gè)變量對(duì)象,存儲(chǔ)三個(gè)模塊中分別選擇的數(shù)據(jù)、定義hash值、相應(yīng)模塊的處理邏輯函數(shù)。
info={ brand:'', carType:'', carSeries:'', pages:['Brand','Type','Series'] };info.selectBrand=function(){ document.title = '選擇商標(biāo)'; 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(){//綁定跳轉(zhuǎn) $('#Brand ul li').click(function(){ info.brand=$(this).find('p').text(); goPage('Type'); }) } function typeEvent(){//綁定跳轉(zhuǎn) $('#Type dd').click(function(){ info.carType=$(this).text(); goPage('Series'); }) } function seriesEvent(){...}③goPage邏輯跳轉(zhuǎn)控制
function goPage(tag) { if ((tag == 'Brand')&&(location.hash.indexOf('Type')!=-1)){ // 后退操作 history.back(); document.title = '選擇商標(biāo)'; }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(); //為默認(rèn)顯示的模塊中的元素綁定相應(yīng)的事件及其他邏輯 $(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(); //執(zhí)行每個(gè)模塊不同的方法 if(typeof(info['select' + tag]) == "function"){ info['select' + tag](); } //展示對(duì)應(yīng)dom $('#' + tag).show();}以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持武林網(wǎng)!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注