所以我有这段代码在倒数计时器达到0后刷新页面。倒计时显示在底部的div中。
<script>
(function countdown(remaining) {
if(remaining === 0)
location.reload(true);
document.getElementById('countdown').innerHTML = remaining;
setTimeout(function(){ countdown(remaining - 1); }, 1000);
})(60);
</script>
<span id="countdown" class="bold"></span>
我希望它以相同的方式刷新,但在页面很长时保持浏览器上的滚动位置。这段代码可以实现吗?
请举例,因为我不太了解javascript ..
由于
答案 0 :(得分:0)
您以前使用过localStorage或cookies吗?这些是用户浏览器的便利部分,您可以在其中实际存储和保存自定义位数据。有关详细信息,请参阅localStorage API。
无论如何,您可以使用localStorage,然后当您的用户滚动时,您可以存储它们的距离。然后,在页面加载时,如果该localStorage键具有值,则向下滚动用户。
我制作了一个片段,但遗憾的是,他们用于片段的iframe不允许我访问localStorage来实际向您展示它是如何运作的。但是,我确实在那里放了一些线条(虽然没有经过测试)但有一些评论试图帮助说明你如何去做它的广泛笔触。
你可以做的唯一其他事情是进行测试,以确保他们的浏览器支持localStorage,然后,如果没有,你可以回到尝试使用cookie或其他方法!< / p>
function updateScrollStuff() {
// this tells us how far down we've scrolled as a number, like '476'
var scrollPosition = $(document).scrollTop();
// I cant access localStorage from the iframe they're using here, but I think this
// would be what you'd want to do with it to store that scroll position
// localStorage.storedScrollPosition = scrollPosition;
// this line is just illustrative, showing you that the number for the scroll position is updating
// every time you scroll - you don't need this for your final purposes
$("#scroll-position").text(scrollPosition + "px");
}
// when the user scrolls, call that function above
$(window).scroll(function() {
updateScrollStuff();
});
// I can't test it here, but on page load I would check to
// see if a value exists, and then scroll to it if it does!
$(window).load(function() {
// again, with local storage blocked all I can do is show you what
// it would look like
// typeof 'undefined' is just a check you can make to see if a variable exists
// if (typeof localStorage.storedScrollPosition != 'undefined') {
// $("html, body").scrollTop(localStorage.storedScrollPosition);
// }
});
body, html {
margin: 0;
padding: 0;
}
.section {
width: 100%;
height: 200px;
}
#section-1 {
background-color: #333333;
}
#section-2 {
background-color: #666666;
}
#section-3 {
background-color: #999999;
}
#section-4 {
background-color: #aaaaaa;
}
#scroll-position {
background-color: black;
color: white;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section-1" class="section"></div>
<div id="section-2" class="section"></div>
<div id="section-3" class="section"></div>
<div id="section-4" class="section"></div>
<h3 id="scroll-position">Scroll to see this change</h3>