uniapp动态修改元素节点样式

一,通过style属性绑定来修改

第一步:肯定是需要获取元素节点
在uniApp项目中没有windouw对象,所以通过document不能直接获取dom节点,vue的refs只对自定义组件有效,对uniapp中的标签不生效。
查看uniapp官网有一个uni.createSelectorQuery() API;可以通过这个属性获取标签的样式,在通过动态绑定样式来修改;
html:

<button type="default" @click="handleFont">点击增大字体</button>
<view class="weibo_box" id='index0' :style="{fontSize:vHeight + 'px'}">

对应的js:

data(){
    
    
	return {
    
    
		vHeight:22
	}
},


handleFont(){
    
    
	const that=this
	uni.createSelectorQuery().select('#index0').boundingClientRect(function (data) {
    
     
	  console.log('元素信息0:',data)
		  that.vHeight +=10
	}).exec()
}

实现的效果:
在这里插入图片描述

二,利用ref来获取dom元素节点

代码:

<button type="default" @click="handleFont">点击增大字体</button>
<view class="weibo_box" id='index1' ref="mydom">
	第二个
</view>
data(){
    
    
	return {
    
    
		vHeight:22
	}
},
//部分代码不相关,省略

handleFont(){
    
    
	const that=this
	that.$refs.mydom.$el.style.fontSize=that.vHeight+=1+'px'
}

实现的效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42349568/article/details/119812394