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>
相关推荐
程序员爱钓鱼2 小时前
Go语言实战案例 — 项目实战篇:简易博客系统(支持评论)
前端·后端·go
excel9 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着9 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友10 小时前
什么是API签名?
前端·后端·安全
会豪12 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子12 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶12 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子12 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_13 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
小徐_233313 小时前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts