一行JS實現滾動到頁面某個元素所在位置(類似JQ ScrollTo插件)


轉自: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所以不存在這個問題)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM