目录
- 一、获取屏幕宽高
- 1.uniapp
- 2.vue
- 二、获取盒子内容宽高
- 1.uniap
- 2.vue
- 总结
获取到屏幕的宽度和高度,可以根据需要将这些值用于布局、样式或其他操作。
一、获取屏幕宽高
1.uniapp
使用uni.getSystemInfo()方法来获取系统信息,包括屏幕的宽度和高度。(注意:uni.getSystemInfo()方法是一个异步方法,因此你需要在success回调函数中处理获取到的屏幕尺寸数据。)
methods: {
getScreenSize() {
uni.getSystemInfo({
success: (res) => {
const screenWidth = res.windowWidth; // 屏幕宽度,单位为px
const screenHeight = res.windowHeight; // 屏幕高度,单位为px
console.log(\’屏幕宽度:\’, screenWidth);
console.log(\’屏幕高度:\’, screenHeight);
},
});
},
},
在需要获取屏幕宽度和高度的地方,调用getScreenSize()方法即可。
mounted() {
this.getScreenSize(); // 在组件或页面加载完成后调用获取屏幕尺寸的方法
},
2.vue
使用window.innerWidth和window.innerHeight获取屏幕的宽高:
const screenWidth = window.innerWidth; // 屏幕宽度
const screenHeight = window.innerHeight; // 屏幕高度
二、获取盒子内容宽高
1.uniap
使用uni.createSelectorQuery()方法来创建一个选择器查询对象,来获取盒子内容撑起的宽度和高度。(注意:uni.createSelectorQuery()方法是一个异步方法,因此你需要在boundingClientRect回调函数中处理获取到的盒子尺寸数据。)
methods: {
getBoxSize() {
uni.createSelectorQuery()
.select(\’.box\’) // 选择你要获取尺寸的盒子元素,这里假设盒子元素的class为box
.boundingClientRect((rect) => {
const boxWidth = rect.width; // 盒子的宽度,单位为px
const boxHeight = rect.height; // 盒子的高度,单位为px
console.log(\’盒子宽度:\’, boxWidth);
console.log(\’盒子高度:\’, boxHeight);
})
.exec();
},
},
在需要获取盒子宽度和高度的地方,调用getBoxSize()方法即可。
mounted() {
this.getBoxSize(); // 在组件或页面加载完成后调用获取盒子尺寸的方法
},
2.vue
在Vue组件中,通过this.$refs访问ref属性,并使用$el获取盒子元素的宽高:
<div ref=\”box\” class=\”box\”></div>
const boxWidth = this.$refs.box.$el.offsetWidth; // 盒子宽度
const boxHeight = this.$refs.box.$el.offsetHeight; // 盒子高度
console.log(boxWidth,boxHeight);
总结
到此这篇关于uniapp和vue如何获取屏幕或盒子内容宽高的文章就介绍到这了,更多相关uniapp和vue获取屏幕内容宽高内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!
您可能感兴趣的文章:
- vue 监听屏幕高度的实例
- Vue屏幕自适应三种实现方法详解
- vue移动端屏幕适配详解