用jquery来实现类似“网易新闻”横向标题滑动的移动端页面
HTML:
<div id="navbar"> <div id='navbar_content' style="left:0px;"> <div class="channel active"> <span>shouye</span> </div> <div class="channel"> <span>shouyeshouye</span> </div> <div class="channel"> <span>shouyeshouyeshouyeshouyes</span> </div> <div class="channel"> <span>shouye</span> </div> <div class="channel"> <span>shouye</span> </div> <div class="channel"> <span>shouye</span> </div> <div class="channel"> <span>shouye</span> </div> <div class="channel"> <span>shouye</span> </div> <div class="channel"> <span>shouye</span> </div> </div> </div> </div>
CSS:
#navbar{ background: rgba(247,247,247,0.95); overflow: hidden; position: relative; text-align: center; font-size: 1em; padding-left: 5px; line-height: 28px; } #navbar_content{ font-size: 1em; text-align: left; white-space: nowrap; position: relative; } .channel{ vertical-align: top; display: inline-block; padding: 0 5px; color: rgba(0,0,0,0.6); font-weight: normal; line-height: 26px; border-bottom: 2px solid transparent; } .channel.active { color: #1c88cd; border-color: #1c88cd; }
JS:
$(function(){ console.log($('#navbar').width()) var total_width=0; var div_arr=$('.channel'); for(var i=0,len=div_arr.length;i<len;i++){ total_width+=div_arr[i].offsetWidth; } console.log(total_width); var x,old_left; $('#navbar_content') .live('touchstart', function(e) { console.log(e.originalEvent.pageX) x = e.originalEvent.targetTouches[0].pageX // anchor point old_left = parseInt(e.currentTarget.style.left); }) .live('touchmove', function(e) { var change = e.originalEvent.targetTouches[0].pageX - x; e.currentTarget.style.left = (old_left+change)+"px"; }) .live('touchend', function(e) { var left = parseInt(e.currentTarget.style.left); var new_left; var window_width=document.body.scrollWidth; if (left < parseInt("-"+total_width)+$('#navbar').width()+100) { new_left = "-"+(total_width-$('#navbar').width()+100); }else if (left > 0) { new_left = '0' } $(e.currentTarget).animate({left: new_left}, 500); e.currentTarget.style.left = new_left; }); });