【发布时间】:2017-12-27 19:42:08
【问题描述】:
我正在使用 React 为自己创建一个副项目网站,以便更好地理解它。我正在尝试为 div 设置动画以在用户滚动到其位置时淡入。我已经成功地使用了滚动事件来触发一个更改 div 类名的函数(根据我的理解,这应该会触发不透明度的转换)。但是,这不起作用;相反,这会导致仅显示 div 中的文本,而没有任何动画。我确定我设置 div 的类名的方式有问题,但不确定是什么,这里是代码:
class Home extends React.Component{
constructor(){
super()
this.state = {
name: "WhatIdo",
firstTransitionPosition: 0
}
this.handleScroll = this.checkForScroll.bind(this)
this.hasBeenSet = false
}
checkForScroll() {
if (window.scrollY >= this.state.firstTransitionPosition && this.hasBeenSet == false) {
console.log("this event is triggering")
this.setState({name: "WhatIdo--visible"})
this.hasBeenSet = true
}
}
componentDidMount(){
var transitionComp = this.refs.moveMe
var topOfElement = transitionComp.getBoundingClientRect().top
var heightOfElement = transitionComp.getBoundingClientRect().height
this.setState({firstTransitionPosition: topOfElement - heightOfElement})
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount(){
window.removeEventListener('scroll', this.handleScroll);
}
render(){
return(
<div>
<h1 className="PageTitle">Portfolio</h1>
<div className="AboutMe">
some stuff here
</div>
<div ref="moveMe" className={this.state.name}>
some more random stuff
</div>
</div>
)
}
}
还有 CSS:
.AboutMe {
border-style: solid;
border-color: black;
border-width: thick;
width: 600px;
height: 300px;
position: relative;
left: 365px;
bottom: 300px;
-moz-animation: fadein 2s;
}
@-moz-keyframes fadein {
from { opacity: 0; }
to { opacity: 2; }
}
.WhatIdo {
border-style: solid;
border-color: black;
border-width: thick;
width: 600px;
height: 300px;
position: relative;
left: 365px;
bottom: 100px;
opacity: 0;
transition: opacity 2s;
}
.WhatIdo--visible {
opacity: 1
}
提前感谢您的帮助!
【问题讨论】:
-
不透明度不采用大于 1 的数字。它是从 0 到 1 的“百分比”值(例如,0.5 表示 50%)
-
@SimonNußbaumer 感谢您注意到这一点!我已经解决了。显示中的主要错误仍然存在。