javascript - Wordpress 在滚动时淡入/淡出(向上和向下)
问题描述
当您在我的 Wordpress 网站上向上/向下滚动时,我希望 div 淡入/淡出。已经在网上找到了这种变化,但不是我想要的。
到目前为止我管理的代码
css
.fade-in-section {
opacity: 0;
transform: translateY(20vh);
visibility: hidden;
transition: opacity 0.6s ease-out, transform 1.2s ease-out;
will-change: opacity, visibility;
}
.fade-in-section.is-visible {
opacity: 1;
transform: none;
visibility: visible;
}
java(虽然不是Wordpress写的):
function FadeInSection(props) {
const [isVisible, setVisible] = React.useState(true);
const domRef = React.useRef();
React.useEffect(() => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => setVisible(entry.isIntersecting));
});
observer.observe(domRef.current);
return () => observer.unobserve(domRef.current);
}, []);
return (
<div
className={`fade-in-section ${isVisible ? 'is-visible' : ''}`}
ref={domRef}
>
{props.children}
</div>
);
}
(沙箱代码和原作者在这里:https ://codesandbox.io/s/beautiful-wiles-k23w5?from-embed )
这可以完美地向下滚动,但我想要相同的动画/过渡向上滚动(屏幕中间只有 2/3 div 可见)
寻找正确的方法,帮助寻找资源来实现这一目标。
解决方案
尝试使用我的解决方案。给你想要淡入/淡出的元素提供淡入淡出类并应用它:
$(document).ready(function() {
$(window).scroll(function() {
var windowBottom = $(this).scrollTop() + $(this).innerHeight();
$(".fade").each(function() {
/* Check the location of each desired element */
var objectBottom = $(this).offset().top + $(this).outerHeight();
/* If the element is completely within bounds of the window, fade it in */
if (objectBottom < windowBottom) { //object comes into view (scrolling down)
if ($(this).css("opacity")==0) {
$(this).fadeTo(500,1);
}
}else{
if ($(this).css("opacity")==1) {
$(this).fadeTo(500,0);
}
}
});
});
});
.fade {
margin: 50px;
padding: 50px;
background-color: red;
opacity: 0;
width: 150px;
height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fade"></div>
<div class="fade"></div>
<div class="fade"></div>
<div class="fade"></div>
<div class="fade"></div>
<div class="fade"></div>
<div class="fade"></div>
推荐阅读
- reactjs - react-router v6 仍然无法区分 '/' 和 '/*'
- angular - ngOnInit() 中的 Angular Transloco 用法
- reactjs - Reactjs 中未定义文件名
- python - 为什么我无法导入已安装的 mysql 模块
- reactjs - 在 React 状态下更改类名
- winapi - 在多线程 CryptSignMessage 调用中重用相同的 CERT_CONTEXT
- powerquery - 使用 PowerQuery 遍历记录列表并调用 API
- javascript - 如何创建一个新的 fetch Response 承诺?
- r - 具有空间自相关的 INLA 模型 - 二元响应,二项式预测器
- c# - 创建新的 ASP.NET Core 6.0 Web API 时出现问题