js實現圖片上下滾動background-position

初晨未涼發表於2020-10-05
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
		<style>
			* {
				margin: 0;
			}
			.a{
				background: pink;
				width: 100%;
				height: 1000px;
				
			}
			.b{
				background: url("images/未標題-1.jpg") no-repeat;
				background-position: 0px 0px;
				width: 100%;
				height: 420px;
				background-attachment: fixed;
				background-size: 100%;
				
			}
			.c{
				background: #FF5B77;
				width: 100%;
				height: 500px;
				
			}
		</style>
	</head>
	<body>
		<div class="a"></div>
		<div class="b">
		</div>
		<div class="c"></div>
	</body>
	<script>
		(function(){
			var b = document.getElementsByClassName("b")[0];
			//獲取頂點到b的高度
			var bof = b.offsetTop;//1000
			window.onscroll = function(){
				//獲取滾動的高度
				var scHeight = document.documentElement.scrollTop;
				console.log(bof - scHeight);
				b.style.backgroundPositionY = (bof - scHeight)*0.5 +"px";
			}
		})();
	</script>
</html>

相關文章