[英]React, z-index for each array element
Not long ago here I recieved answer, how increase each img as member of array. 不久前,我收到了答案,如何增加每个img作为数组的成员。 Somehow the same principle don't wokrs for z-index (increaced img should lie on top of the rest), though console displays that z-index changed.
尽管控制台显示z-index发生了变化,但z-index的相同原理不知所措(增加的img应该位于其余部分的顶部)。 Why?
为什么?
class Article extends React.Component{
constructor(props) {
super(props)
this.state = {showIncreaced: null}
this.getImgStyle = this.getImgStyle.bind(this);
this.increase = this.increase.bind(this);
}
increase (incId) {
this.setState({showIncreaced: incId})
}
getImgStyle (id) {
return {
width: '20vw',
marginRight: '0.5vw',
marginLeft: '0.5vw',
zIndex: this.state.showIncreaced === id ? '10' : '0',
transform: this.state.showIncreaced === id ? 'scale(1.5, 1.5)' : 'scale(1, 1)'
};
}
render(){
const TipStyle={
marginBottom: '10px'
}
return(
<div style={TipStyle}>
<h2 style={{marginBottom: '1px'}}>{this.props.name}</h2>
<div>
{[1,2,3].map((id) => {
return <img style={this.getImgStyle(id)} src={this.props[`img${id}`]} onMouseOver={this.increase.bind(this, id)} onMouseOut={this.increase} />
})}
</div>
</div>
);
}
}
https://jsfiddle.net/Nata_Hamster/fbs3m4jL/ https://jsfiddle.net/Nata_Hamster/fbs3m4jL/
add position: 'relative',
to the object returned by getImgStyle
because z-index
works only when postion
is set to something else than static
(its default value). 将
position: 'relative',
添加到getImgStyle
返回的对象,因为z-index
仅在postion
设置为static
(默认值)以外的其他值时才起作用。 The easiest way is to use relative
because the element is still part of the document flow. 最简单的方法是使用
relative
因为元素仍然是文档流的一部分。
https://jsfiddle.net/fbs3m4jL/7/ https://jsfiddle.net/fbs3m4jL/7/
This is because the position
of your image elements are static
by default. 这是因为默认情况下图像元素的
position
是static
的。
If you update the image position to say position:absolute;
如果您将图像位置更新为“
position:absolute;
, then the zIndex
values will work as expected. ,则
zIndex
值将按预期工作。 The catch with this is that you need to position the images with left coordinates so that they sit next to each other. 要注意的是,您需要使用左坐标定位图像,使它们彼此相邻放置。 Here is an updated version of
getImgStyle
that illustrates the concept: 这是说明概念的
getImgStyle
的更新版本:
getImgStyle (id) {
return {
position:'absolute', // Set absolute position
left: `${(id-1) * 100}px`, // Calculate a left coordinate for image
width: '20vw',
marginRight: '0.5vw',
marginLeft: '0.5vw',
zIndex: this.state.showIncreaced === id ? '10' : '0',
transform: this.state.showIncreaced === id ? 'scale(1.5, 1.5)' : 'scale(1, 1)'
};
}
Here is a working jsFiddle if you'd like to see it in action 这是一个工作的jsFiddle,如果您想看到它的实际效果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.