심시은*_*심시은 5 css transition ecmascript-6 reactjs
我每 3 秒更改一个 div 的 className(状态更改,使用 setInterval)。每个类别都有不同的背景图像。
我想在背景图像发生变化时使用过渡 CSS 淡入和淡出它们。我看到了一些更简单情况的示例,但是我有两个以上的元素需要更改/并通过状态更改来更改图片。
我怎样才能做到这一点?
我将代码上传到:https://stackblitz.com/edit/react-ubxffz 但我无法在此页面上上传图像,因此暂时将其替换为该页面中的背景颜色。
这是图像幻灯片组件。
const imgUrls = [
1,2,3
];
class ImageSlide extends Component {
render() {
const { url } = this.props;
const Text=...
return (
<div>
<div className={`pic${url}`}>
<p className="p1_1">{Text.p1_1}</p>
</div>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
这是App组件,它调用ImageSlide。
class App extends Component {
constructor (props) {
super(props);
currentImageIndex: 0,
};
}
// ...
componentDidMount() {
this.interval = setInterval(() => {
this.nextSlide(); //this function change the index state.
}, 3000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
// ...
<ImageSlide url={imgUrls[this.state.currentImageIndex]} />
Run Code Online (Sandbox Code Playgroud)
这是每个类的 css,设置背景图像。
.pic1 {
background-image: url('images/img_01.png');
}
.pic2 {
background-image: url('images/img_02.png');
}
.pic3 {
background-image: url('images/img_03.png');
}
Run Code Online (Sandbox Code Playgroud)
它的工作原理如下:要淡入淡出背景:您需要将两个具有不同背景图像的元素堆叠在彼此之上,然后进行交叉淡入淡出
stackblitz中的工作代码。
无框架的工作代码:
const imgUrls = [
1,2,3
];
let currentIndex = 0;
const lastIndex = imgUrls.length - 1;
const nextSlide = () => {
currentIndex++;
currentIndex = currentIndex % (lastIndex + 1)
// @See https://css-tricks.com/restart-css-animation/
const elm = document.getElementById('root')
.querySelector('[class^="pic"],[class*=" pix"]');
elm.className = `pic${currentIndex+1}`
const newone = elm.cloneNode(true);
elm.parentNode.replaceChild(newone, elm);
}
interval = setInterval(() => {
console.log()
nextSlide(); //this function change the index state.
}, 3000);Run Code Online (Sandbox Code Playgroud)
#root {
position: relative;
width: 640px;
height: 480px;
}
#root .front,
#root .back {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#root .front {
z-index: 2;
opacity: 0;
}
#root .back {
z-index: 1;
opacity: 1;
}
#root [class^="pic"] .front,
#root [class*=" pic"] .front {
-webkit-animation: in 3s 0s;
animation: in 3s 0s;
}
#root .pic1 .front,
#root .pic2 .back {
background-image: url("https://picsum.photos/640/480?image=1");
}
#root .pic1.init .back {
background-image: none;
}
#root .pic2 .front,
#root .pic3 .back {
background-image: url("https://picsum.photos/640/480?image=2");
}
#root .pic3 .front,
#root .pic1 .back {
background-image: url("https://picsum.photos/640/480?image=3");
}
@-webkit-keyframes in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}Run Code Online (Sandbox Code Playgroud)
<div id="root">
<div class="pic1 init">
<div class="front"></div>
<div class="back"></div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7470 次 |
| 最近记录: |