赞
踩
- <!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>Tab栏切换懒加载</title>
- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
- <style>
- * {
- margin: 0;
- padding: 0;
- }
-
- .tabs {
- display: flex;
- }
-
- .tabs li {
- width: 100px;
- height: 50px;
- text-decoration: none;
- list-style-type: none;
- border: 1px solid #ccc;
- margin-left: 10px;
- }
-
- .tabs-box {
- width: 330px;
- background-color: burlywood;
- height: 100px;
- display: none;
- }
-
- .active {
- background-color: steelblue;
- color: #fff;
- }
-
- .boxOne {
- display: block;
- }
- </style>
- </head>
-
- <body>
- <ul class="tabs">
- <li class="active">1</li>
- <li>2</li>
- <li>3</li>
- </ul>
- <div class="boxs">
- <div class="tabs-box boxOne" data-attrval="diyi">1</div>
- <div class="tabs-box" data-attrval="dier">2</div>
- <div class="tabs-box" data-attrval="disan">3</div>
- </div>
- </body>
- </html>

- // tab 栏切换
- $('.tabs li').on('click', function () {
- $(this).addClass('active').siblings().removeClass('active')
- $(this)
- .parent()
- .next()
- .children()
- .eq($(this).index())
- .css('display', 'block')
- .siblings()
- .css('display', 'none')
- })
-
- // 懒加载
- if (window?.IntersectionObserver) {
- let items = [...document.getElementsByClassName('tabs-box')]
- let io = new IntersectionObserver(
- (entries) => {
- entries.forEach((item) => {
- // intersectionRatio === 1说明该元素完全暴露出来
- if (item.intersectionRatio) {
- item.target.style.backgroundColor = 'yellow'
- // 对应div内的代码
- if (item.target.dataset.attrval === 'diyi') {
- // 简单的js代码
- item.target.innerHTML = 'diyi'
- } else if (item.target.dataset.attrval === 'dier') {
- item.target.innerHTML = 'dier'
- } else if (item.target.dataset.attrval === 'disan') {
- item.target.innerHTML = 'disan'
- }
- }
- })
- },
- {
- root: null,
- rootMargin: '0px 0px',
- threshold: 0.1 // 阀值设为1,当只有比例达到1时才触发回调函数
- }
- )
- items.forEach((item) => io.observe(item))
- }

各位有更好的方法可以指出
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。