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

效果

代码

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

html 复制代码
<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>

扩展

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

效果

代码

html 复制代码
<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>
相关推荐
子兮曰3 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭3 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路6 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒7 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol8 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉8 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau8 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生8 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼8 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君879978 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter