轉自:https://www.cnblogs.com/jimaww/p/10007433.html
在實現滾動到頁面指定位置時一般使用的都是JQuery的ScrollTo插件( 具體可見:ScrollTo:平滑滾動到頁面指定位置 )
但是我們也可以使用幾行原生js實現此功能:
打開此頁面:http://www.runoob.com/try/try.php?filename=tryjsref_html_blur
那么在輸入這幾行代碼就可以啦:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>菜鳥教程(runoob.com)</title> </head> <body> <div style="height:200px;width:300px;margin:20px"></div> <div style="height:200px;width:300px;margin:20px"></div> <div style="height:200px;width:300px;margin:20px"></div> <div style="height:200px;width:300px;margin:20px"></div> <div id="greenid" style="height:200px;width:300px;margin:20px" tabindex="4"></div> <div style="height:200px;width:300px;margin:20px"></div> <div style="height:200px;width:300px;margin:20px"></div> <div style="height:200px;width:300px;margin:20px"></div> <div style="height:200px;width:300px;margin:20px"></div> <a href="http://www.runoob.com//" tabindex="2"> runoob.com 菜鳥教程</a><br /> <a id="focusid" href="http://www.google.com/" tabindex="1">Google</a><br /> <a href="http://www.microsoft.com/" tabindex="3">Microsoft</a> </body> <script> document.querySelector('#greenid').focus(); //document.querySelector('#focusid').focus(); </script>
原理:利用tabindex和focus,因為focus只能聚焦在input,button,a之類可聚焦的標簽上,所以要給div加上tabindex使其可以被focus。
注意:如果元素已經被focus了那么再次focus不會觸發滾動條滾動至此元素,記得在再次觸發滾動到此focus元素之前先blur即可(demo是兩個元素來回focus所以不存在這個問題)。