我正在尝试使网页在元素完全位于窗口中时仅显示一个元素。当元素不在窗口中时,我要淡出,而当它完全可见时,我希望它淡入。
作为一个初学者,我要做的唯一一件事就是完全删除上一个类并添加相反的内容,但是无论我如何尝试完成此操作(主要是围绕元素[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-除外)
只有我的不透明度命令起作用,我的“淡入淡出”动画不起作用...关于我应该尝试什么的任何建议?
答案 0 :(得分:0)
<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>
此外,我推荐这篇文章是为了了解how-to-check-if-any-part-of-an-element-is-out-of-the-viewport-with-vanilla-js。
希望有帮助。