最近项目其中一个需求是wap滑动导航,因为开发时间不长,本打算想偷懒,用swipe的插件实现这个需求,以前一直用这个插件,来实现首页banner图的轮播之类,滑动和滚动的特效,挺实和方便的一个插件。
进入测试阶段,收到一个bug,就是在ios11-webview中,页面滑到底部,从新回到顶部时,滑动导航会忽闪忽现。仔细查阅官方文档,并无什么卵用。最后只好用js实现wap滑动导航。不说了,上代码!
CSS
* {padding: 0;margin: 0}
ul li {list-style: none;}
.page-wrapper {max-width: 720px;margin: 0 auto;}
.main-box {width: 100%;height: 50px;line-height: 50px;background-color:
.main-box ul {margin: 0 10px;height: 50px;position: absolute;width: auto;overflow-x: scroll;left: 0;}
.main-box ul li {float: left;margin-right: 10px;}
.log_box{height: 30px;margin: 50px 0;}
.clearfix:after,.page-row:after{visibility: hidden;display: block;font-size: 0;content: " ";clear: both;height: 0}
.clearfix,.page-row{*zoom: 1}
.hide{display: none;}
::-webkit-scrollbar {display: none}
复制代码
HTML
<div class="page-wrapper">
<div class="main-box" id="halder_ID">
<ul id="tab_ul" class="clearfix">
<li id="tab_li">栏目一</li>
<li>栏目二</li>
<li>栏目三</li>
<li>栏目四</li>
<li>栏目五</li>
<li>栏目六</li>
<li>栏目日</li>
</ul>
</div>
<div id="show_itembox">
<div>1</div>
<div class="hide">2</div>
<div class="hide">3</div>
<div class="hide">4</div>
<div class="hide">5</div>
<div class="hide">6</div>
<div class="hide">7</div>
</div>
</div>
复制代码
Javascript
window.onload = function() {
var contal_ul = document.getElementById("tab_ul"); //获取移动目标元素
var contal_li = contal_ul.getElementsByTagName('li'); //获取点击目标元素
var getLi = document.getElementById('tab_li'); //获取某个li
var getLi_Val = window.getComputedStyle(getLi, null); //获取li的元素属性
var tag_width = parseInt(getLi_Val.marginRight) + parseInt(getLi_Val.width) * (contal_li.length + 1) + 20; //经过计算,获取ul的宽度
contal_ul.style.width = tag_width + 'px'; //设置ul的宽度
function touchedMoveFun(ev) { //移动方法
ev = ev || window.ev;
var screen_w = window.innerWidth; //获取手机屏幕宽度
var offset_left = contal_ul.offsetLeft; //获取目标元素距离屏幕左边的位移
var coordinateX = ev.changedTouches[0].clientX; //获取触摸点的X位置
var setting_left = 0; //声明位移的变量
if (parseFloat(coordinateX) >= screen_w / 2) { //限制左边的最大位移
setting_left = 10;
} else if (parseFloat(coordinateX) <= -(screen_w - tag_width)) { //限制右边的最大位移
setting_left = screen_w - tag_width;
} else {
setting_left = parseFloat(coordinateX) - (tag_width / 4); //自由位移
}
contal_ul.style.left = setting_left + 'px'; //设置位移
}
//添加事件
document.addEventListener("touchstart",function() {document.touchmove = null;},false);
document.addEventListener("touchmove", touchedMoveFun, false);
document.addEventListener("touchend",function() {document.touchmove = null;},false);
//点击切换tab
for (var y = 0; y < contal_li.length; y++) {
contal_li[y].index = y;
contal_li[y].onclick = function() {
var _this = this.index;
var showBox = document.getElementById("show_itembox");
var showItem = showBox.getElementsByTagName('div');
for (var i = 0; i < showItem.length; i++) {
showItem[i].style.display = 'none';
}
showItem[_this].style.display = 'block';
}
}
}
复制代码
效果图
如代码有错误的,或者遇到问题,请指教!互相学习!