uni-app nvue position absolute top和left怎么能居中显示不支持百分比呢
时间: 2025-02-16 12:17:36 浏览: 70
uni-app 使用 NVue 的时候,如果想要让 `position: absolute` 元素水平垂直居中显示,但又因为不支持百分比直接设置 `top` 和 `left` 属性为 `50%` 或者 `auto`,你可以通过计算元素的尺寸并添加偏移量来实现。这里是一个示例:
```html
<template>
<view class="container">
<view :style="{ position: 'absolute', display: 'flex', alignItems: 'center', justifyContent: 'center' }" ref="centerElement">
<!-- 这里是你需要居中的内容 -->
<text>Centered Element</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 存储元素的实际宽度和高度
elementWidth: 0,
elementHeight: 0
};
},
mounted() {
this.$refs.centerElement.addEventListener('touchstart', (e) => {
this.elementWidth = e.target.offsetWidth;
this.elementHeight = e.target.offsetHeight;
this.updatePosition();
});
},
methods: {
updatePosition() {
const containerRect = this.$refs.container.getBoundingClientRect(); // 获取容器元素的矩形
const centerX = containerRect.width / 2; // 水平居中点
const centerY = containerRect.height / 2; // 垂直居中点
// 更新元素的位置
this.$refs.centerElement.style.left = `${centerX - this.elementWidth / 2}px`;
this.$refs.centerElement.style.top = `${centerY - this.elementHeight / 2}px`;
}
}
};
</script>
<style scoped>
.container {
position: relative;
}
</style>
```
在这个例子中,当元素加载完成或用户触碰时,我们获取元素的尺寸,并根据容器的中心坐标计算出新的 `left` 和 `top` 值。由于uni-app的限制,你需要手动更新这些值。
阅读全文
相关推荐

















