JS_动态定位效果
html提供了一个功能:点击一个a标签,只要在href属性中写上#id就可以定位到那个id的位置,但是为了更好的用户体验,考虑使用缓动公式来达到这个需求。
缓动公式网上搜搜就有好多,五花八门的。自己写了一个相对比较好理解的,比较笨的方法用在很多个小例子上面。下面po下我的代码
html:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <div class="theContent"> 2 3 <div class="nav"> 4 <ul> 5 <li id="nav1" class="title">导航一</li> 6 <li id="nav2" class="title">导航二</li> 7 <li id="nav3" class="title">导航三</li> 8 <li id="nav4" class="title">导航四</li> 9 </ul> 10 </div> 11 <div class="content" id="txt1">内容一</div> 12 <div class="content" id="txt2">内容二</div> 13 <div class="content" id="txt3">内容三</div> 14 <div class="content" id="txt4">内容四</div> 15 16 </div>
css代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ul{ 2 list-style: none; 3 } 4 .nav{ 5 width: 100%; 6 height: 200px; 7 background:pink; 8 padding-top:50px; 9 } 10 .nav ul{ 11 width: 410px; 12 height: 40px; 13 margin:0 auto; 14 } 15 .nav ul li{ 16 float: left; 17 height: 40px; 18 width: 100px; 19 line-height:40px; 20 text-align: center; 21 border: 1px solid #000; 22 cursor: pointer; 23 } 24 .content{ 25 width:100%; 26 height: 400px; 27 } 28 #nav1,#txt1{ 29 background: #FFE1FF; 30 } 31 #nav2,#txt2{ 32 background: #FFD39B; 33 } 34 #nav3,#txt3{ 35 background: #FFBBFF; 36 } 37 #nav4,#txt4{ 38 background: #FFAEB9; 39 } 40 .theContent{ 41 height: 2300px; 42 }
js:
1 window.addEventListener("load",function(){ 2 3 var nav = getClass("title"); 4 var txt = getClass("content"); 5 var len = nav.length; 6 7 for(var i=0;i<len;i++){ 8 (function(m){ 9 nav[i].addEventListener("click",function(){ 10 //document.documentElement.scrollTop = document.body.scrollTop = txt[m].offsetTop; 11 var des = txt[m].offsetTop; 12 var start = window.pageYOffset || document.documentElement.offsetTop; 13 moveSlowly(des,start); 14 }) 15 })(i) 16 } 17 18 }) 19 20 var timer = null; 21 22 function moveSlowly(des,start,time){ 23 clearInterval(timer); 24 var speedTime = time || 100; 25 var start = start || 0; 26 var distance = des - start; 27 var speed = distance/speedTime; 28 var i = 1; 29 var pos = start; 30 31 timer = setInterval(function(){ 32 33 if(i == speedTime){ 34 pos = des; 35 document.documentElement.scrollTop = document.body.scrollTop = pos; 36 clearInterval(timer); 37 }else{ 38 pos = pos + speed; 39 document.documentElement.scrollTop = document.body.scrollTop = pos; 40 console.log(pos) 41 i++; 42 } 43 44 },1) 45 } 46 47 48 function getClass(clsName,Parent){ 49 var oParent = Parent ? document.getElementById(Parent): document; 50 var eles = []; 51 var elements = oParent.getElementsByTagName("*"); 52 var len = elements.length; 53 54 for(var i =0;i<len;i++){ 55 if(clsName == elements[i].className){ 56 eles.push(elements[i]) 57 } 58 } 59 60 return eles; 61 }
效果展示:
内容一
内容二
内容三
内容四
以上内容,如有错误请指出,不甚感激。