当前位置:首页 > 编程笔记 > 正文
已解决

uni-app:js修改元素样式(宽度、外边距)

来自网友在路上 158858提问 提问时间:2023-10-06 18:35:01阅读次数: 58

最佳答案 问答题库588位专家为你答疑解惑

效果

代码

1、在<view>元素上添加一个ref属性,用于在JavaScript代码中获取对该元素的引用:<view ref="myView" id="mybox"></view>

2、获取元素引用 :const viewElement = this.$refs.myView.$el;

3、修改元素宽度:viewElement.style.width = '100px';

4、修改元素左外边距: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>

扩展

这种情况可能运行到手机端会出现拥堵,无法正常运行,现举实例解决手机端出现的问题

效果

代码

<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>

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"uni-app:js修改元素样式(宽度、外边距)":http://eshow365.cn/6-16423-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!