uniapp调整webview的大小与位置解决遮挡问题的办法
作者:printf_824
这篇文章主要介绍了如何在uniapp中使用webview时控制其大小和位置,以避免挡住顶部内容,并提供了一个示例代码,文中通过代码介绍的非常详细,需要的朋友可以参考下
起因:
uniapp使用webview时默认的是全屏显示
通过fullscreen="false"和webview-styles="style"两个属性可以控制大小,但是依然会挡住顶部的东西,只能以百分比的单位去控制宽高且无法控制位置
解决方案:
众所周知,query.select().boundingClientRect可以获取元素的高度,$getAppWebview可以获取webview实例,uni.getSystemInfoSync()可以获取屏幕高度,因此我们就可以通过控制webview定位来让一些内容显示出来,并且可以修改webview实例的高度,以下是我使用时的示例,仅供参考:
<view class="base_header"> <mHeader ref="base_header"></mHeader> </view> <view class="main"> <view class="bage_close"> <close color="#000" ref="bage_close"></close> </view> <web-view :fullscreen="false" src="xxx"></web-view> </view>
onMounted(() => {
const instance = getCurrentInstance();
const query = uni.createSelectorQuery().in(instance);
const {
windowHeight
} = uni.getSystemInfoSync(); // 屏幕高度(单位:px)
console.log("屏幕高度:", windowHeight);
if (instance && instance.proxy) {
const currentWebview = instance.proxy.$scope?.$getAppWebview();
if (currentWebview) {
nextTick(() => {
setTimeout(() => {
let closeHeight = 0;
let baseHeaderHeight = 0;
query
.select(".base_header")
.boundingClientRect((res) => {
if (res && res.height) {
baseHeaderHeight = res.height;
} else {
baseHeaderHeight = 100; // 默认高度
}
})
.select(".bage_close")
.boundingClientRect((res) => {
if (res && res.height) {
closeHeight = res.height + 100;
} else {
closeHeight = 100; // 默认高度
}
})
.exec(() => {
const totalTop = closeHeight + baseHeaderHeight;
console.log("Calculated totalTop:", totalTop);
const wv = currentWebview.children()?.[0];
if (wv) {
wv.setStyle({
top: `${totalTop}px`,
height: `${windowHeight-totalTop-30}px`,
zIndex: -1,
});
}
});
}, 300);
});
}
}
});假设遇见了点击事件问题,记得调整内容的层级(position: relative;z-index: 1000;)
总结
到此这篇关于uniapp调整webview的大小与位置解决遮挡问题的文章就介绍到这了,更多相关uniapp调整webview大小与位置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
