【问题标题】:how to automatically scroll down a html page?如何自动向下滚动html页面?
【发布时间】:2012-02-05 03:10:05
【问题描述】:

我正在尝试在主页向下大约 500px 之后开始每个页面,类似于这个网站:http://unionstationdenver.com/

在主页之后查看页面时,您会注意到,您会自动向下滚动而不会发出通知,但您可以向上滚动以再次体验特色滑块。

我玩过scrolledHeight,但我认为这不是我需要的????

基本上,我在所有内容页面的顶部都有一个特色部分,但在您向上滚动之前,您应该无法看到此部分。有什么帮助吗?

【问题讨论】:

  • 你可能想看看这个。 stackoverflow.com/questions/8773405/…
  • 甜蜜!我唯一担心的是您仍然可以看到滚动的动画。所以我点击的每个页面都会加载前 500 像素,然后滚动到它下面的内容。这会让用户感到厌烦。想法?

标签: javascript html css scroll height


【解决方案1】:

您可以为此使用.scrollIntoView()。它会将特定元素带入视口。

例子:

document.getElementById( 'bottom' ).scrollIntoView();

演示:http://jsfiddle.net/ThinkingStiff/DG8yR/

脚本:

function top() {
    document.getElementById( 'top' ).scrollIntoView();    
};

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );
};

bottom();

HTML:

<div id="top">top</div>
<div id="bottom">bottom</div>

CSS:

#top {
    border: 1px solid black;
    height: 3000px;
}

#bottom {
    border: 1px solid red;
}

【讨论】:

  • 此解决方案在 IE 下适用于我,但不适用于 Chrome。有什么想法吗?
  • 更多信息:它在第一个页面加载时在 Chrome 中有效,但在刷新时无效。我认为这是由于这个错误:code.google.com/p/chromium/issues/detail?id=280460。如果我硬刷新它可以工作的页面,即单击 URL 栏并按 Enter。但是像页面刷新或单击刷新按钮(或按 F5)这样的软重置不起作用。
【解决方案2】:

您可以使用两种不同的技术来实现这一点。

第一个是用javascript:设置可滚动元素的scrollTop属性(例如document.body.scrollTop = 1000;)。

第二个是将链接设置为指向页面中的特定ID,例如

<a href="mypage.html#sectionOne">section one</a>

如果在您的目标页面中您将拥有该 ID,则该页面将自动滚动。

【讨论】:

  • 对于你的第一个技术,你是如何得到它的,所以它可以归结为特定元素的位置?
  • 是的,我有关于做主播的想法,但这是最后的手段。我只是不知道这些人是怎么做到的unionstationdenver.com
  • @Wex 在纯 javascript 中,您可以像这样在文档中找到元素的位置:var topPosition = document.getElementById("myElement").offsetTop;
  • @Hambone 你可以在这个脚本link 中看到他们正在使用窗口对象的 scrollTo 方法。更多信息:scrollTo on mozilla
【解决方案3】:

这里是使用纯 JavaScript 的示例

function scrollpage() {		
	function f() 
	{
		window.scrollTo(0,i);
		if(status==0) {
   			i=i+40;
			if(i>=Height){	status=1; } 
		} else {
			i=i-40;
			if(i<=1){	status=0; }  // if you don't want continue scroll then remove this line
		}
	setTimeout( f, 0.01 );
	}f();
}
var Height=document.documentElement.scrollHeight;
var i=1,j=Height,status=0;
scrollpage();
</script>
<style type="text/css">

	#top { border: 1px solid black;  height: 20000px; }
	#bottom { border: 1px solid red; }

</style>
<div id="top">top</div>
<div id="bottom">bottom</div>

【讨论】:

    【解决方案4】:

    使用document.scrollTop 更改文档的位置。将document 的scrollTop 设置为您网站特色部分的bottom

    【讨论】:

    • scrollTop 仅适用于 DOM 元素,不适用于文档
    猜你喜欢
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2020-09-05
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    相关资源
    最近更新 更多