javascript - 如何在一个 javascript 函数中连续实现相互矛盾的 css 类以在页面上创建淡入/淡出效果?
问题描述
我试图让一个网页在元素完全在窗口中时只显示一个元素。当元素不在窗口中时,我想淡出,当它完全进入视野时,我希望它淡入。
作为一个初学者,我唯一能想到的就是完全删除前一个类并添加相反的类,但无论我如何尝试实现这一点(主要是围绕我的元素[i].style.animation = 'none' 或 null 并更改 if 语句的语法。)
我的 javascript(在 HTML 文件中):
<script>
window.onscroll=function(){fade()};
function fade(){
var elements = document.querySelectorAll('.block1,.block2');
for (var i = 0; i < elements.length; i++) {
if(elements[i].offsetTop>window.pageYOffset && elements[i].offsetTop+elements[i].clientHeight<window.pageYOffset+window.innerHeight){
elements[i].style.animation='none';
elements[i].style.animation=null;
elements[i].className+=" pageFade";
elements[i].style.opacity="1";
}
else{
elements[i].style.animation='none';
elements[i].style.animation=null;
elements[i].className+=" outFade";
elements[i].style.opacity="0";
}
}
}
</script>
我的 CSS
.pageFade{
animation:reveal 1.5s ease-in-out 1;
-webkit-animation-name:reveal 1.5s ease-out 1;
}
@keyframes reveal{
0%{opacity:0}
100%{opacity:1}
}
.outFade{
animation:unreveal 1.5s ease-in-out 1;
-webkit-animation-name:unreveal 1.5s ease-out 1;
}
@keyframes unreveal{
0%{opacity:1}
100%{opacity:0}
}
(-webkit- 除外)
只有我的不透明度命令在起作用,我的“淡入淡出”动画不起作用......关于我应该尝试什么的任何建议?
解决方案
- 使用脚本添加/删除一个类。
- 然后,在类中放置您想要的样式。
<div class="block">BLOCK 1</div>
<div class="block">BLOCK 2</div>
<style>
.block {
width: 90px; height: 150px; background: red; margin: 6px;
transition: opacity .9s ease-in-out;
opacity: 1;
}
.fade { opacity: 0; }
</style>
<script>
function handleFade(){
// use const in a var that is never reasigned
const elements = document.querySelectorAll('.block');
// using forEach is clearer and more declarative
elements.forEach(element => {
// add a more expressive name to the conditions
const condition1 = element.offsetTop > window.pageYOffset;
const condition2 = element.offsetTop + element.clientHeight <
window.pageYOffset + window.innerHeight;
// clean your if condition
if(condition1 && condition2) element.classList.remove('fade');
else element.classList.add('fade');
});
}
// execute handleFade at the beginning in case user does not scroll.
handleFade();
// remove redundant anonymous function
window.onscroll = handleFade;
</script>
此外,我推荐这篇文章是为了了解如何检查 -if-any-part-of-an-element-is-out-of-the-viewport-with-vanilla-js。
希望能帮助到你。
推荐阅读
- php - 如何在提交多个数据时显示百分比进度条
- macos - 更新后 MAMP 不启动
- php - PHP preg_match_all 在自己的服务器上不起作用,但在 PHP Sandbox 上起作用
- groovy - 如何增加 vaadin 进度条的大小(厚度)
- angularjs - 弹簧,角度 Js
- sql-server - 如何将 Windows 批处理文件中的日期格式设为“yyyymmdd”?
- python - 如何在没有回溯的情况下重新引发相同的异常?
- rabbitmq - Sockjs 重新连接尝试未订阅 RabbitMQ 队列
- aem - AEM 和 Jackrabbit Oak 中的同时会话登录
- php - 使用php转换数组数据