javascript 滚动插入元素动画特效
监听窗体滚动条,新的元素会以 左移、右移、淡出、淡入 等各种方式插入到文档流中
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>javascript 滚动插入元素动画特效</title> <style> * { box-sizing: border-box; } body { background-color: #efedd6; display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 0; overflow-x: hidden; } h1 { margin: 10px; } .box { background-color: steelblue; color: #fff; display: flex; align-items: center; justify-content: center; width: 400px; height: 200px; margin: 10px; border-radius: 10px; box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3); transform: translateX(400%); transition: transform 0.4s ease; } .box:nth-of-type(even) { transform: translateX(-400%); } .box.show { transform: translateX(0); } .box h2 { font-size: 45px; } .box img{ width: 400px; height: 200px; } </style> </head> <body> <div> <h1>javascript 滚动插入元素动画特效</h1> <div class="box"> <h2>Content1</h2> </div> <div class="box"> <h2>Content</h2> </div> <div class="box"> <h2>Content2</h2> </div> <div class="box"> <h2>Content3</h2> </div> <div class="box"> <h2>Content4</h2> </div> <div class="box"> <h2>Content5</h2> </div> <div class="box"> <img src="https://www.uxqr.com/background.php?t1.png"> </div> <div class="box"> <img src="https://www.uxqr.com/background.php?t2.png"> </div> <div class="box"> <img src="https://www.uxqr.com/background.php?t3.png"> </div> <div class="box"> <img src="https://www.uxqr.com/background.php?t4.png"> </div> </div> <script> const boxes = document.querySelectorAll('.box') window.addEventListener('scroll', checkBoxes) checkBoxes() function checkBoxes() { const triggerBottom = window.innerHeight / 5 * 4 boxes.forEach(box => { const boxTop = box.getBoundingClientRect().top if (boxTop < triggerBottom) { box.classList.add('show') } else { box.classList.remove('show') } }) } </script> </body>
电脑端的朋友可以直接点击上面的【运行代码】查看效果。注:在线预览可能遇到bug,代码保存到本地后可解决!
写在最后:
zblog纯净主题食用方法
css代码:
.block .post { transform: translateX(400%); transition: transform 0.4s ease; } .block .show { transform: translateX(0); }
js代码:
const boxes = document.querySelectorAll('.block .post') window.addEventListener('scroll', checkBoxes) checkBoxes() function checkBoxes() { const triggerBottom = window.innerHeight / 5 * 4 boxes.forEach(box => { const boxTop = box.getBoundingClientRect().top if (boxTop < triggerBottom) { box.classList.add('show') } else { box.classList.remove('show') } }) }
版权声明:本文由 LzxBlog 发布,如需转载请注明出处。