[英]How to show a child div without changing the position of that element's siblings?
我有一个登录表单中的div html标记,该表单中的div显示了一个错误。 错误div位于父div的顶部。 触发错误后,我希望错误div位于div内,而表单不会关闭,但这不会发生。 我已经在子div中使用了position: absolute
,但是它位于父div的左上角。 我也使用了z-index
,以使子div位于父div上方,但父始终降低像素高度,即子div的大小。 让我向您展示示例:
<div id='formulario' style={{height: 400px}}>
{this.props.auth.error && <div id='erro' style={{height:'15px'}}>Nao foi possivel fazer o login!</div>}
<div id='login'>
...
</div>
</div>
当this.props.auth.error
为true时,将出现错误,并且表单ID大小将变为415px。 我怎么离开#formulatrio
与大小DIV 400px
和#login
DIV到位出现错误的时候?
仅供您测试,我添加了背景。
<style>
#formulario {
display: grid;
align-content: center;
width: 400px;
height: 400px;
background: grey;
}
#erro {
position: relative;
width: 100%;
height: 15px;
background: yellow;
text-align: center;
}
</style>
<div id='formulario'>
{this.props.auth.error && <div id='erro'>Nao foi possivel fazer o login!</div>}
<div id='login'>
...
</div>
</div>
增加top CSS属性以将登录div向下移动到某个位置,并添加了可视化背景。
class MaintainPosition extends React.Component { render() { return ( <div id="formulario" style={{ height: "400px", backgroundColor: "lightblue" }} > {this.props.auth.error && ( <div id="erro" style={{ height: "15px", color: "red" }}> Nao foi possivel fazer o login! </div> )} <div id="login"> scroll down to toggle error </div> </div> ); } } class App extends React.Component { constructor(props) { super(props); this.state = { error: true }; } render() { return ( <div className="App"> <MaintainPosition auth={{ error: this.state.error }} /> <button onClick={() => this.setState({ error: !this.state.error })}> toggle error </button> </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
#err { } #formulario { position: relative; } #login { position: absolute; width: 100%; top: 20px; background-color: gray; } #root {text-align: center}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
像这样吗
此处的关键是将父对象设置为relative
以便孩子知道使用引用。
$('button').on('click', function() { $('#erro').toggle(); });
#formulario { border: 1px solid #EEE; position: relative; } #erro { background-color: rgba(255,0,0,.5); text-align: center; position: absolute; width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Show/Hide Error</button> <hr> <div id='formulario' style='height: 400px'> <div id='erro' style='height: 15px'>Nao foi possivel fazer o login!</div> <div id='login'> Some<br/> Login<br/> Stuff<br/> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.