如何自动向下滚动 html 页面?

问题描述 投票:0回答:5

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

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

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

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

javascript html css scroll height
5个回答
52
投票

您可以为此使用

.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;
}

3
投票

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

第一个是使用 javascript:设置可滚动元素的 scrollTop 属性(例如

document.body.scrollTop = 1000;
)。

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

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

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


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>


2
投票

使用

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


0
投票
<?php
        echo '<script type="text/javascript">document.scrollTop = 99999999;</script>';
        ob_flush();
        ob_end_flush();
        flush();
        ob_start();
?>

对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.