js多张图片滚动切换

看到别的网站有这样一个效果觉得很有意思,有点像公众号里面的svg效果,就尝试用代码实现了一下。实现思路大致如下。

顺便给大家分享一个有意思的插件,有兴趣的朋友可以研究一下怎么利用这个插件实现:
Parallax scrolling with CSS variables | basicScroll

html部分:

  1.  固定一个容器用来装三张图片(相对定位);
  2.  给容器设置一张默认背景图片;
  3.  容器内新增两个块级容器用来存放另外两张图片,
  4.  容器内两个块级容器设置z-index用来层级展示(绝对定位);

js部分:

  1.  获取容器内的两张图片dom元素;
  2.  监听当前浏览器的滚动事件;
  3.  根据滚动距离与图片位置进行动态计算;

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>template</title>
		<style>
			body {
				height: 300vh;
				background-color: black;
			}

			.behind {
				height: 100vh;
			}

			.container {
				width: 100%;
				height: 100vh;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.box {
				width: 120px;
				height: 208px;
				background: url(./image/3.png) no-repeat center center;
				background-size: 100% 100%;
				margin: 0 auto;
				position: relative;
				overflow: hidden;
			}

			.box1 {
				position: absolute;
				top: 0;
				left: 0;
				width: 120px;
				height: 208px;
				background: url(./image/2.png) no-repeat center center;
				background-size: 100% 100%;
				z-index: 1;
			}

			.box2 {
				position: absolute;
				top: 0;
				left: 0;
				width: 120px;
				height: 208px;
				background: url(./image/1.png) no-repeat center center;
				background-size: 100% 100%;
				z-index: 2;
			}
		</style>
	</head>
	<body>
		<div class="behind"></div>
		<div class="container">
			<div class="box">
				<div class="box1"></div>
				<div class="box2"></div>
			</div>
		</div>
	</body>
	<script>
		// 定义两张图片的滚动位置
		let top1 = 520;
		let top2 = 660;
		// 获取图片的DOM元素
		const box1 = document.querySelector('.box1')
		const box2 = document.querySelector('.box2')
		// 监听浏览器的滚动
		document.addEventListener('scroll', function() {
			const scrollTop = document.documentElement.scrollTop
			// 如果当前滚动位置大于第一张图片的位置,则进行样式赋值, top * 3为滚动大小幅度
			if (scrollTop > top1) {
				const top = (scrollTop - top1) / 2
				if (top < 0) top = 0
				box2.style.top = `-${top * 3}px`
			}
			// 大于第二章图片的位置,则同上操作
			if (scrollTop > top2) {
				const top = (scrollTop - top2) / 2
				if (top < 0) top = 0
				box1.style.top = `-${top * 3}px`
			}
		})
	</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值