左右可移动的导航,简单样式
<script type="text/javascript" src="jquery.min.js"></script> <style type="text/css"> #topMenuDiv{ margin:0px; padding:0px; line-height:25px; background:#F2F2F2; border-top:1px solid #E5E5E5; border-bottom:1px solid #E5E5E5; color: #333; } #topMenuDiv .btn-left{ float:left; width: 20px; text-align: center; z-index: 20; background: #f2f2f2; cursor:pointer; border-right: solid 1px #ccc; } #topMenuDiv .btn-right{ float:right; width: 20px; text-align: center; z-index: 20; background: #f2f2f2; cursor:pointer; border-left: solid 1px #ccc; } #topMenuDiv .btn-left:hover{ color: #33AECC; } #topMenuDiv .btn-right:hover{ color: #33AECC; } #topMenuDiv .menuDiv{ line-height:25px; white-space:nowrap; overflow:hidden; display:block; } .menuDiv ul{ width:100%; line-height:25px; list-style-type:none; padding:0; margin:0; } .menuDiv ul li{ width: 120px; line-height:25px; display: inline-block; cursor:pointer; border-right: solid 1px #ccc; text-align:center; list-style: none; } .menuDiv ul li:hover{ color: #33AECC; } </style> <div id="topMenuDiv" > <div class="btn-left" onclick="move('left');" > <b><</b> </div> <div class="btn-right" onclick="move('right');"> <b>></b> </div> <div class="menuDiv"> <!--需要连着写li,否则会出现li左边有空隙的问题--> <ul> <li>测试1</li><li>测试2</li><li>测试3</li><li>测试4</li><li>测试5</li><li>测试6</li> </ul> </div> </div> <script> /** li移动方法 */ function move(val){ var liWidth = $(".menuDiv li").width()+1;//加上边框 var ulLeft = $(".menuDiv ul").css("left"); if(ulLeft!=null&&ulLeft!=""){ ulLeft = ulLeft.replace("px","");
if(ulLeft=="auto"){
ulLeft = 0;
}
//向右移动校验 if(val!="left"&&ulLeft>=0){ alert("已经到了第一选项!"); return; } //向左移动校验 if(val=="left"){ var liCount = $(".menuDiv li").length; var totalLiWidth = liCount * liWidth; var menuDivWidth=$(".menuDiv").width(); if(totalLiWidth<=menuDivWidth){ //如果li的总长度没有超出ul的长度,没有必要点左移 return; }
var remainingWidth = totalLiWidth + Number(ulLeft); if(remainingWidth<=menuDivWidth)){ alert("已经到了最后选项!"); return; } } }else{ //没有找到left属性 return; } var moveVal = 0; if(val=="left"){ moveVal = Number(ulLeft)-Number(liWidth); }else{ moveVal = Number(ulLeft)+Number(liWidth); } $(".menuDiv ul").css("position","relative");
if($(".menuDiv ul").is(":animated")){
//如果正在滑动,暂时不向下执行
return;
}
$(".menuDiv ul").animate({"left":moveVal + "px"}); } </script>
效果图: