布局时经常用到 position: fixed; 可以将元素固定定位在页面的指定位置,如下图所示:
提交按钮为固定定位,但当页面中有输入框(例如input)时,点击输入时会有软键盘从底部弹起,一旦页面内容高度过高时,提交按钮会覆盖在页面内容上,导致布局混乱,有时还会遮挡住页面内容,影响使用,解决方法如下:
获取屏幕高度,监听resize获取屏幕高度变化
<div class="submitView" v-if="hideShow == true">
<div class="submitBtn">提交</div>
</div>
<style lang="scss">
.submitView{
width: 100%;
padding: 0 0.4rem;
box-sizing: border-box;
position: fixed;
bottom: 0rem;
left: 0;
display: flex;
align-items: center;
justify-content: space-between;
.submitBtn{
width: 3rem;
height: 0.76rem;
background: #00095B;
border-radius: 0.08rem;
margin-bottom: 0.6rem;
font-size: 0.36rem;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
}
}
</style>
export default {
data() {
return {
originalHeight: 0, //屏幕原始高度
screenHeight: 0, //屏幕实时高度
hideShow: true, //按钮是否显示
}
}
},
mounted(){
//获取首次进入页面的原始高度
this.originalHeight = document.documentElement.clientHeight;
//监听页面高度实时变化
window.addEventListener('resize', this.watchResize);
},
watch: {
//监听屏幕高度变化
screenHeight(newHeight) {
this.hideShow = this.originalHeight <= newHeight;
}
},
beforeDestroy() {
// 销毁
window.removeEventListener("resize", this.watchResize);
},
methods:{
//监听的内容--实时变化的窗口高度
watchResize() {
this.screenHeight = document.documentElement.clientHeight;
},
},
此方法可以通过监听屏幕实际高度的变化,决定固定元素是否显示,即当屏幕高度小于原始高度时,隐藏底部按钮,这样就不会影响页面内容的显示与使用了。