【发布时间】:2018-03-24 01:53:49
【问题描述】:
我想达到this one这样的效果 在 React 网页中,但不使用 jQuery。我一直在寻找该库的替代品,但没有结果。我见过很多类似的问题,但每个问题都是用 jQuery 回答的。
效果基本上是在我向下滚动浏览不同部分时更改徽标(以及页面中的其他元素)的颜色。
有谁知道实现这一目标的方法吗?
【问题讨论】:
标签: javascript reactjs colors
我想达到this one这样的效果 在 React 网页中,但不使用 jQuery。我一直在寻找该库的替代品,但没有结果。我见过很多类似的问题,但每个问题都是用 jQuery 回答的。
效果基本上是在我向下滚动浏览不同部分时更改徽标(以及页面中的其他元素)的颜色。
有谁知道实现这一目标的方法吗?
【问题讨论】:
标签: javascript reactjs colors
可以做到这一点的一种方法是将徽标动态地居中到它们自己的容器中,有点像模拟位置固定,但使用绝对位置,因此每个徽标都包含在它们自己的部分中,而不是像位置固定那样全局。 这样,当您滚动到下一部分时,第二部分会覆盖第一部分,使其看起来像是在过渡。
我在这里创建了一个概念证明:
https://codesandbox.io/s/9k4o3zoo
注意:此演示是概念验证,可以通过使用请求动画帧和限制等功能来提高性能。
代码:
class App extends React.Component {
state = {};
handleScroll = e => {
if (!this.logo1) return;
const pageY = e.pageY;
// 600 is the height of each section
this.setState(prevState => ({
y: Math.abs(pageY),
y2: Math.abs(pageY) - 600
}));
};
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
render() {
const { y, y2 } = this.state;
return (
<div>
<section className="first">
<h1
className="logo"
style={{ transform: `translateY(${y}px)` }}
ref={logo => {
this.logo1 = logo;
}}
>
YOUR LOGO
</h1>
</section>
<section className="second">
<h1
className="logo"
style={{ transform: `translateY(${y2}px)` }}
ref={logo => {
this.logo2 = logo;
}}
>
YOUR LOGO
</h1>
</section>
</div>
);
}
}
CSS 将是:
section {
height: 600px;
width: 100%;
position: relative;
font-family: helvetica, arial;
font-size: 25px;
overflow: hidden;
}
.first {
background: salmon;
z-index: 1;
}
.first .logo {
color: black;
}
.second {
background: royalBlue;
z-index: 2;
}
.second .logo {
color: red;
}
.logo {
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 230px;
height: 30px;
}
【讨论】: