当div中绑定数据,给它一个属性overflow-y: scroll,添加长度大小,使其能够出现滚动条;每次刷新的时候滚动条总是会出现在最上方,这使我很头疼,经过查阅网上资料,返现两种方法可行。如下:
第一种方案
将上一个页面的div的scrolltop距离长度记录在cookie中,然后通过js调整刷新页面时的长度记录,代码如下:
js代码:
<script>var _h = 0;function SetH(o) {_h = o.scrollTopSetCookie("a", _h)}window.onload = function () {document.getElementById("x").scrollTop = GetCookie("a");//页面加载时设置scrolltop高度 }function SetCookie(sName, sValue) {document.cookie = sName + "=" + escape(sValue) + "; ";}function GetCookie(sName) {var aCookie = document.cookie.split("; ");for (var i = 0; i < aCookie.length; i++) {var aCrumb = aCookie[i].split("=");if (sName == aCrumb[0])return unescape(aCrumb[1]);}return 0;}</script>
html中代码如下:
<div id="x" style="height: 200px; overflow: scroll" onscroll="SetH(this)"><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p><p>1</p></div>
第二种方案
1.通过div的onscroll事件记录滚动条的scrollTop值,设置到document.cookie
2.页面加载时再读取document.cookie的值,设置给div的scrollTop
js代码实现:
<script type="text/javascript">function KeepScrollBar() {var scrollPos;if (typeof window.pageYOffset != 'undefined') {scrollPos = window.pageYOffset;}else if (typeof document.body != 'undefined') {scrollPos = document.getElementById('divContent').scrollTop;}document.cookie = "scrollTop=" + scrollPos; }window.onload = function (){if (document.cookie.match(/scrollTop=([^;]+)(;|$)/) != null) {var arr = document.cookie.match(/scrollTop=([^;]+)(;|$)/); document.getElementById('divContent').scrollTop = parseInt(arr[1]);}}</script>
html:
<div class="content" data-role="tab-content" data-id="course-a" runat="server" id="divContent" style="height: 365px; overflow-y: scroll" onscroll= "KeepScrollBar()"><p> 1</p><p> 2</p><p> 3</p><p> 4</p><p> 5</p><p> 6</p><p> 7</p><p> 8</p><p> 9</p><p> 10</p><p> 11</p><p> 12</p><p> 13</p><p> 14</p><p> 15</p><p> 16</p> </div>
如果觉得《页面的div中有滚动条 js实现刷新页面后回到记录时滚动条的位置》对你有帮助,请点赞、收藏,并留下你的观点哦!