平滑滚动div id到div id不起作用?

时间:2016-11-17 10:17:52

标签: javascript jquery html css

您好我正在建立一个网站,现在我想尝试制作当你点击一个div你顺利滚动到另一个div但它不能正常工作是我正在使用的代码:

<script>
$("#knop").click(function() {
    $('html, body').animate({
        scrollTop: $("#nieuws").offset().top
    }, 2000);
});
</script>

两个div:

<div class="nieuwsbrief" id="knop" style="text-align:center; cursor: pointer;">BLIJF OP DE HOOGTE<br> MET ONZE NIEUWSBRIEF</div>

<div id="nieuws"></div>

谢谢!

1 个答案:

答案 0 :(得分:0)

这是一种使用普通的香草javascript在两个div之间向后和向前滚动的方法:

&#13;
&#13;
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');

var verticalGapInPixels = 624;
var scrollIncrementInPixels = 2;
var numberOfIntervals = (verticalGapInPixels / scrollIncrementInPixels);

function scrollBetweenDivs() {
	var i = 0;
	var scrollIncrement = (this.id === 'div1' ? scrollIncrementInPixels : -scrollIncrementInPixels);

    var scrollByInterval = setInterval(
    	function(){
    		window.scrollBy(0,scrollIncrement);
    		i++;
    		if (i >= numberOfIntervals) {clearInterval(scrollByInterval);}
    	},1
    );
}

div1.addEventListener('click',scrollBetweenDivs,false);
div2.addEventListener('click',scrollBetweenDivs,false);
&#13;
div {
width: 120px;
height: 120px;
margin: 12px auto 500px;
text-align: center;
border: 2px solid rgb(63,63,63);
cursor: pointer;
}

div p {
font-size: 12px;
}

#div1 {
background: rgb(191,191,191);
}

#div2 {
background: rgb(127,127,127);
}
&#13;
<div id="div1">
<h2>Div 1</h2>
<p>Click to Scroll<br />Down to Div 2</p>
</div>

<div id="div2">
<h2>Div 2</h2>
<p>Click to Scroll<br />Up to Div 1</p>
</div>
&#13;
&#13;
&#13;