我有一个来自登录表单的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
的{{1}} div和400px
的div留在原处?
答案 0 :(得分:0)
为便于测试,我添加了背景。
<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>
答案 1 :(得分:0)
增加顶部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>
答案 2 :(得分:0)
像这样吗?
此处的关键是将父级设置为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>