Effect
code
1.
<view>
Add anref
attribute on the element to get a reference to the element in JavaScript code: <view ref=" myView " id="mybox"></view>2. Get the element reference: const viewElement = this.$refs.myView . $el;
3. Modify the element width: viewElement.style.width = '100px';
4. Modify the left margin of the element: viewElement.style.marginLeft = '20px';
<template>
<view>
<view ref="myView" id="mybox"></view>
</view>
</template>
<script>
export default {
data() {
return {
};
},
mounted() {
// 获取元素引用
const viewElement = this.$refs.myView.$el;
// 修改元素宽度
viewElement.style.width = '100px';
// 修改元素左外边距
viewElement.style.marginLeft = '20px';
},
methods: {
},
};
</script>
<style>
#mybox {
width: 500px;
height: 200px;
border: 1px solid black;
}
</style>
Expand
This situation may cause congestion on the mobile phone and prevent normal operation. Here is an example to solve the problem on the mobile phone.
Effect
code
<template>
<view>
<view id="test" ref="test">这是一个元素</view>
<view id="text" :style="{ marginTop: marginTop + 'px' }">被修改内容</view>
</view>
</template>
<script>
export default {
data() {
return {
query: null, // 声明查询选择器对象
marginTop: 0, // 子元素的外边距
};
},
onReady() {
this.query = uni.createSelectorQuery(); // 创建查询选择器对象
this.query
.select('#test')
.fields({
size: true
}, (res) => {
const parentHeight = res.height;
console.log('父元素的高度:' + parentHeight);
})
.exec(
this.query
.select('#text')
.fields({
size: true
}, (res) => {
const sontHeight = res.height;
console.log('子元素的高度:' + sontHeight);
const marginTop = sontHeight / 4;
this.marginTop = marginTop;
})
);
},
};
</script>
<style>
#test {
border: 1px solid black;
height: 300px;
}
#text {
border: 1px solid black;
height: 200px;
}
</style>