标签:
css
*{ margin: 0; padding: 0; } .m-a{ float: left; width: 100px; } .m-a a{ display: block; height: 30px; line-height: 30px; text-align: center; border: 1px solid #000; } .m-a a.on{ background-color: #ccc; } .con{ float: left; width: 300px; height: 300px; border: 2px solid green; }
html
<div class="m-a" id="J_a"> <a href="ajax.php?area=suzhou">苏州</a> <a href="ajax.php?area=wuxi">无锡</a> <a href="ajax.php?area=changzhou">常州</a> <a href="ajax.php?area=zhenjiang">镇江</a> <a href="ajax.php?area=nanjing">南京</a> <a href="ajax.php?area=yangzhou">扬州</a> <a href="ajax.php?area=nantong">南通</a> <a href="ajax.php?area=huaian">淮安</a> <a href="ajax.php?area=taizhou">泰州</a> <a href="ajax.php?area=lianyungang">连云港</a> <a href="ajax.php?area=yancheng">盐城</a> <a href="ajax.php?area=suqian">宿迁</a> <a href="ajax.php?area=xuzhou">徐州</a> </div> <div class="con" id="J_con"></div>
Js
var cityCon = [ {con: ‘苏州 苏州‘}, {con: ‘无锡 无锡‘}, {con: ‘常州 常州‘}, {con: ‘镇江 镇江‘}, {con: ‘南京 南京‘}, {con: ‘扬州 扬州‘}, {con: ‘南通 南通‘}, {con: ‘淮安 淮安‘}, {con: ‘泰州 泰州‘}, {con: ‘连云港 连云港‘}, {con: ‘盐城 盐城‘}, {con: ‘宿迁 宿迁‘}, {con: ‘徐州 徐州‘} ]; var eleMenuOn = null; var eleMenu = $(‘#J_a a‘).on(‘click‘, function(event) { var $this = $(this), $oCon = $(‘#J_con‘), query = this.href.split(‘?‘)[1]; eleMenuOn && eleMenuOn.removeClass(‘on‘); eleMenuOn = $this.addClass(‘on‘); $oCon.html(cityCon[$this.index()].con); /* * ajax请求 * */ // history处理 var title = this.innerHTML; document.title = title; // history.pushState({}, ‘页面标题‘, ‘xxx.html‘) // history.pushState(state, title, url) => 向浏览器添加记录 // state:要跳转的url对应的信息 // title:页面标题 // url:要跳转的url地址,不能跨域 if (event && /\d/.test(event.button)) { // 判断鼠标事件 history.pushState({title: title}, title, location.href.split(‘?‘)[0] + ‘?‘ + query); } event.preventDefault(); }); // popstate history.go和history.back(包括用户按浏览器历史前进后退按钮)触发,并且页面无刷的时候(由于使用pushState修改了history)会触发popstate事件,事件发生时浏览器会从history中取出URL和对应的state对象替换当前的URL和history.state。通过event.state也可以获取history.state。 window.addEventListener(‘popstate‘, function() { var query = location.href.split(‘?‘)[1], eleTarget = null; eleMenu.each(function() { if (this.href.split(‘?‘)[1] == query) { eleTarget = this; $(this).trigger(‘click‘); } }); $(eleTarget).trigger(‘click‘); });
8. H5 pushState/popstate + ajax开发无刷新页面
标签:
原文地址:http://www.cnblogs.com/zouxinping/p/5441940.html