首页 > 解决方案 > 如何在一个 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- 除外)

只有我的不透明度命令在起作用,我的“淡入淡出”动画不起作用......关于我应该尝试什么的任何建议?

标签: javascripthtmlcss

解决方案


  1. 使用脚本添加/删除一个类。
  2. 然后,在类中放置您想要的样式。

<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

希望能帮助到你。


推荐阅读