更改DOM元素onscroll不起作用

时间:2017-10-26 13:18:19

标签: javascript dom scroll

当用户在页面上向下滚动50px时,我试图更改导航。在我的consol日志中,我可以看到它检测到滚动,但它只显示0,而不是新的新数量..我在这里做错了什么?



<!DOCTYPE html>
<html>
<head>
	<title>Scroll Test</title>
	<script type="text/javascript">
			
		window.onload = oppstart;

		function oppstart() {
			document.getElementById("doc").onscroll = scroll;
		}

		function scroll() {
			var element = document.getElementById("doc");
			var y = element.scrollTop;
			console.log(y);
			document.getElementById("utskrift").innerHTML = y + " px";
			if (y === 50) {
				document.getElementById("navigation").style.backgroundColor = "red";
			}
		}

	</script>
	<style type="text/css">

		body {
			overflow: auto;
		}
		
		#navigation {
			height: 30vh;
			background-color: black;
			overflow: auto;
		}

		#main {
			height: 200vh;
		}

	</style>
</head>
<body id="doc">
<nav id="navigation"></nav>
<div id="main">
<p id="utskrift"></p>
</div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

只需更改

element.scrollTop;

window.scrollY

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	<title>Scroll Test</title>
	<script type="text/javascript">
			
		window.onload = oppstart;

		function oppstart() {
			document.getElementById("doc").onscroll = scroll;
		}

		function scroll() {
			var y = window.scrollY;
			console.log(y);
			document.getElementById("utskrift").innerHTML = y + " px";
			if (y === 50) {
				document.getElementById("navigation").style.backgroundColor = "red";
			}
		}

	</script>
	<style type="text/css">

		body {
			overflow: auto;
		}
		
		#navigation {
			height: 30vh;
			background-color: black;
			overflow: auto;
		}

		#main {
			height: 200vh;
		}

	</style>
</head>
<body id="doc">
<nav id="navigation"></nav>
<div id="main">
<p id="utskrift"></p>
</div>
</body>
</html>
&#13;
&#13;
&#13;