繁体   English   中英

React,每个数组元素的z-index

[英]React, z-index for each array element

不久前,我收到了答案,如何增加每个img作为数组的成员。 尽管控制台显示z-index发生了变化,但z-index的相同原理不知所措(增加的img应该位于其余部分的顶部)。 为什么? 在此处输入图片说明

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/

position: 'relative',添加到getImgStyle返回的对象,因为z-index仅在postion设置为static (默认值)以外的其他值时才起作用。 最简单的方法是使用relative因为元素仍然是文档流的一部分。

https://jsfiddle.net/fbs3m4jL/7/

这是因为默认情况下图像元素的positionstatic的。

如果您将图像位置更新为“ position:absolute; ,则zIndex值将按预期工作。 要注意的是,您需要使用左坐标定位图像,使它们彼此相邻放置。 这是说明概念的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)'
    };
  }

这是一个工作的jsFiddle,如果您想看到它的实际效果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM