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

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

猜你喜欢

转载自blog.csdn.net/weixin_46001736/article/details/133377264