vue 获取dom的css属性值

本文介绍在Vue.js中如何使用ref属性获取DOM元素如div和img的高度、宽度及图片源路径。通过mounted生命周期钩子函数,演示了如何访问和打印这些样式属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <div id="topInfo" ref="topInfo" style="width: 200px;height: 200px;background-color: #0bb20c">
    <img id="imgInfo" ref="imgInfo" src="./20151205231902_xe2kG.jpeg" alt="" height="200px"  >
  </div>
</template>
 
<script>
    export default {
        name: "center",
      mounted() {
//div 标签获取的方法
        let topInfowidth = this.$refs.topInfo.style.width;
        let topInfoheight = this.$refs.topInfo.style.height;
        console.log("topInfo:"+topInfowidth+"  "+topInfoheight)
 
        console.log("=================================================")
//img 标签获取的方法
        let imgInfowidth = this.$refs.imgInfo.width;
        let imgInfoheight = this.$refs.imgInfo.height;
        console.log("imgInfo:"+imgInfowidth+"  "+imgInfoheight)
        let src = this.$refs.imgInfo.src;
        console.log("src:"+src)
 
      }   //获取dom元素高度通过在标签里面定义ref属性,用this.$refs.自定义名称.offsetHight;去获取。
    }
</script>
 
<style scoped>
  #topInfo{
  overflow: hidden;
}
</style>

  

let imgInfo = this.$refs.imgInfo;
console.log(imgInfo)
if (imgInfo) {
let src = this.$refs.imgInfo.src; //有时候这一段会报错说获取不到,那么就要判断一下
console.log(src)
}

 1、div 包含img,在li标签里面

<li id="imgBox" >
<div class="box"> //不知道为什么之前试的时候img 总是不能被div包含,现在突然又可以了,神奇
<img src="../home/20151205231902_xe2kG.jpeg" ref="imgInfo" :onload="drawImage_box()" class="imsg">
</div>
<i class="delImg" v-on:click="delImg(key)"> X </i>
</li>


注意:需要在mounted中才能获取到

CSSStyleDeclaration {0: "width", 1: "height", 2: "background-color", 3: "padding-bottom", alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}
alignContent:""
alignItems:""
alignSelf:""
alignmentBaseline:""
all:""
animation:""
animationDelay:""
animationDirection:""
animationDuration:""
animationFillMode:""
animationIterationCount:""
animationName:""
animationPlayState:""
animationTimingFunction:""
backdropFilter:""
backfaceVisibility:""
background:""
backgroundAttachment:""
backgroundBlendMode:""
backgroundClip:""
backgroundColor:"rgb(11, 178, 12)"
backgroundImage:""
backgroundOrigin:""
backgroundPosition:""
backgroundPositionX:""
backgroundPositionY:""
backgroundRepeat:""
backgroundRepeatX:""
backgroundRepeatY:""
backgroundSize:""
baselineShift:""
blockSize:""
border:""
borderBottom:""
borderBottomColor:""
borderBottomLeftRadius:""
borderBottomRightRadius:""
borderBottomStyle:""
borderBottomWidth:""
borderCollapse:""
borderColor:""
borderImage:""
borderImageOutset:""
borderImageRepeat:""
borderImageSlice:""
borderImageSource:""
borderImageWidth:""
borderLeft:""
borderLeftColor:""
borderLeftStyle:""
borderLeftWidth:""
borderRadius:""
borderRight:""
borderRightColor:""
borderRightStyle:""
borderRightWidth:""
borderSpacing:""
borderStyle:""
borderTop:""
borderTopColor:""
borderTopLeftRadius:""
borderTopRightRadius:""
borderTopStyle:""
borderTopWidth:""
borderWidth:""
bottom:""
boxShadow:""
boxSizing:""
breakAfter:""
breakBefore:""
breakInside:""
bufferedRendering:""
captionSide:""
caretColor:""
clear:""
clip:""
clipPath:""
clipRule:""
color:""
colorInterpolation:""
colorInterpolationFilters:""
colorRendering:""
columnCount:""
columnFill:""
columnGap:""
columnRule:""
columnRuleColor:""
columnRuleStyle:""
columnRuleWidth:""
columnSpan:""
columnWidth:""
columns:""
contain:""
content:""
counterIncrement:""
counterReset:""
cssFloat:""
cssText:"width: 20px; height: 100px; background-color: rgb(11, 178, 12); padding-bottom: 55px;"
cursor:""
cx:""
cy:""
d:""
direction:""
display:""
dominantBaseline:""
emptyCells:""
fill:""
fillOpacity:""
fillRule:""
filter:""
flex:""
flexBasis:""
flexDirection:""
flexFlow:""
flexGrow:""
flexShrink:""
flexWrap:""
float:""
floodColor:""
floodOpacity:""
font:""
fontDisplay:""
fontFamily:""
fontFeatureSettings:""
fontKerning:""
fontSize:""
fontSizeAdjust:""
fontStretch:""
fontStyle:""
fontVariant:""
fontVariantCaps:""
fontVariantLigatures:""
fontVariantNumeric:""
fontVariationSettings:""
fontWeight:""
grid:""
gridArea:""
gridAutoColumns:""
gridAutoFlow:""
gridAutoRows:""
gridColumn:""
gridColumnEnd:""
gridColumnGap:""
gridColumnStart:""
gridGap:""
gridRow:""
gridRowEnd:""
gridRowGap:""
gridRowStart:""
gridTemplate:""
gridTemplateAreas:""
gridTemplateColumns:""
gridTemplateRows:""
height:"100px"
hyphens:""
imageRendering:""
inlineSize:""
isolation:""
justifyContent:""
justifyItems:""
justifySelf:""
left:""
length:4
letterSpacing:""
lightingColor:""
lineHeight:""
lineHeightStep:""
listStyle:""
listStyleImage:""
listStylePosition:""
listStyleType:""
margin:""
marginBottom:""
marginLeft:""
marginRight:""
marginTop:""
marker:""
markerEnd:""
markerMid:""
markerStart:""
mask:""
maskSourceType:""
maskType:""
maxBlockSize:""
maxHeight:""
maxInlineSize:""
maxWidth:""
maxZoom:""
minBlockSize:""
minHeight:""
minInlineSize:""
minWidth:""
minZoom:""
mixBlendMode:""
objectFit:""
objectPosition:""
offset:""
offsetAnchor:""
offsetDistance:""
offsetPath:""
offsetPosition:""
offsetRotate:""
opacity:""
order:""
orientation:""
orphans:""
outline:""
outlineColor:""
outlineOffset:""
outlineStyle:""
outlineWidth:""
overflow:""
overflowAnchor:""
overflowWrap:""
overflowX:""
overflowY:""
padding:""
paddingBottom:"55px"
paddingLeft:""
paddingRight:""
paddingTop:""
page:""
pageBreakAfter:""
pageBreakBefore:""
pageBreakInside:""
paintOrder:""
parentRule:null
perspective:""
perspectiveOrigin:""
placeContent:""
placeItems:""
placeSelf:""
pointerEvents:""
position:""
quotes:""
r:""
resize:""
right:""
rotate:""
rx:""
ry:""
scale:""
scrollBehavior:""
shapeImageThreshold:""
shapeMargin:""
shapeOutside:""
shapeRendering:""
size:""
speak:""
src:""
stopColor:""
stopOpacity:""
stroke:""
strokeDasharray:""
strokeDashoffset:""
strokeLinecap:""
strokeLinejoin:""
strokeMiterlimit:""
strokeOpacity:""
strokeWidth:""
tabSize:""
tableLayout:""
textAlign:""
textAlignLast:""
textAnchor:""
textCombineUpright:""
textDecoration:""
textDecorationColor:""
textDecorationLine:""
textDecorationSkip:""
textDecorationStyle:""
textIndent:""
textJustify:""
textOrientation:""
textOverflow:""
textRendering:""
textShadow:""
textSizeAdjust:""
textTransform:""
textUnderlinePosition:""
top:""
touchAction:""
transform:""
transformBox:""
transformOrigin:""
transformStyle:""
transition:""
transitionDelay:""
transitionDuration:""
transitionProperty:""
transitionTimingFunction:""
translate:""
unicodeBidi:""
unicodeRange:""
userSelect:""
userZoom:""
vectorEffect:""
verticalAlign:""
visibility:""
webkitAppRegion:""
webkitAppearance:""
webkitBackgroundClip:""
webkitBackgroundOrigin:""
webkitBorderAfter:""
webkitBorderAfterColor:""
webkitBorderAfterStyle:""
webkitBorderAfterWidth:""
webkitBorderBefore:""
webkitBorderBeforeColor:""
webkitBorderBeforeStyle:""
webkitBorderBeforeWidth:""
webkitBorderEnd:""
webkitBorderEndColor:""
webkitBorderEndStyle:""
webkitBorderEndWidth:""
webkitBorderHorizontalSpacing:""
webkitBorderImage:""
webkitBorderStart:""
webkitBorderStartColor:""
webkitBorderStartStyle:""
webkitBorderStartWidth:""
webkitBorderVerticalSpacing:""
webkitBoxAlign:""
webkitBoxDecorationBreak:""
webkitBoxDirection:""
webkitBoxFlex:""
webkitBoxFlexGroup:""
webkitBoxLines:""
webkitBoxOrdinalGroup:""
webkitBoxOrient:""
webkitBoxPack:""
webkitBoxReflect:""
webkitColumnBreakAfter:""
webkitColumnBreakBefore:""
webkitColumnBreakInside:""
webkitFontSizeDelta:""
webkitFontSmoothing:""
webkitHighlight:""
webkitHyphenateCharacter:""
webkitLineBreak:""
webkitLineClamp:""
webkitLocale:""
webkitLogicalHeight:""
webkitLogicalWidth:""
webkitMarginAfter:""
webkitMarginAfterCollapse:""
webkitMarginBefore:""
webkitMarginBeforeCollapse:""
webkitMarginBottomCollapse:""
webkitMarginCollapse:""
webkitMarginEnd:""
webkitMarginStart:""
webkitMarginTopCollapse:""
webkitMask:""
webkitMaskBoxImage:""
webkitMaskBoxImageOutset:""
webkitMaskBoxImageRepeat:""
webkitMaskBoxImageSlice:""
webkitMaskBoxImageSource:""
webkitMaskBoxImageWidth:""
webkitMaskClip:""
webkitMaskComposite:""
webkitMaskImage:""
webkitMaskOrigin:""
webkitMaskPosition:""
webkitMaskPositionX:""
webkitMaskPositionY:""
webkitMaskRepeat:""
webkitMaskRepeatX:""
webkitMaskRepeatY:""
webkitMaskSize:""
webkitMaxLogicalHeight:""
webkitMaxLogicalWidth:""
webkitMinLogicalHeight:""
webkitMinLogicalWidth:""
webkitPaddingAfter:""
webkitPaddingBefore:""
webkitPaddingEnd:""
webkitPaddingStart:""
webkitPerspectiveOriginX:""
webkitPerspectiveOriginY:""
webkitPrintColorAdjust:""
webkitRtlOrdering:""
webkitRubyPosition:""
webkitTapHighlightColor:""
webkitTextCombine:""
webkitTextDecorationsInEffect:""
webkitTextEmphasis:""
webkitTextEmphasisColor:""
webkitTextEmphasisPosition:""
webkitTextEmphasisStyle:""
webkitTextFillColor:""
webkitTextOrientation:""
webkitTextSecurity:""
webkitTextStroke:""
webkitTextStrokeColor:""
webkitTextStrokeWidth:""
webkitTransformOriginX:""
webkitTransformOriginY:""
webkitTransformOriginZ:""
webkitUserDrag:""
webkitUserModify:""
webkitWritingMode:""
whiteSpace:""
widows:""
width:"20px"
willChange:""
wordBreak:""
wordSpacing:""
wordWrap:""
writingMode:""
x:""
y:""
zIndex:""
zoom:""
0:"width"
1:"height"
2:"background-color"
3:"padding-bottom"

转载于:https://www.cnblogs.com/itchenfirst/p/9983854.html

<think>好的,用户想在Vue3中动态修改CSS属性,我需要根据提供的引用内容来回答。首先,查看用户提供的引用,虽然都是关于Vue.js的动态样式修改,但需要确认是否适用于Vue3。 用户提供的引用[1]提到使用data定义属性,v-bind绑定,然后在方法中修改Vue3的Composition API可能会有不同的写法,比如使用ref或reactive。引用[2]提到了类绑定、内联样式和计算属性,这些在Vue3中仍然适用,但可能需要调整语法。引用[3]展示了类绑定的示例,Vue3中的类绑定语法应该类似,但需要确认是否有变化。 首先,需要确定Vue3中动态修改CSS的方法是否与Vue2相同。Vue3支持Options API和Composition API,所以需要分别说明。然后,用户可能需要具体的示例代码,比如内联样式绑定、类绑定、计算属性等。 要确保回答覆盖不同的方法,比如对象语法、数组语法、内联样式绑定,以及使用Composition API的示例。另外,需要注意Vue3中可能废弃了一些语法或引入了新的特性,比如在setup函数中使用ref等。 需要检查是否有遗漏的方法,比如使用CSS变量或动态样式表,但根据引用内容,可能主要围绕类绑定和内联样式。还要提醒用户注意响应式数据的处理,比如使用ref或reactive来确保视图更新。 最后,生成相关问题时要涵盖常见的后续疑问,比如性能优化、动态类与内联样式的区别、响应式问题等。</think>在Vue3中动态修改CSS属性,可以通过以下四种方式实现(含代码示例): ### 一、内联样式绑定(对象语法) ```vue <template> <div :style="{ color: textColor, fontSize: fontSize + 'px' }">动态文字样式</div> </template> <script setup> import { ref } from 'vue' const textColor = ref('#f00') const fontSize = ref(16) setTimeout(() => { textColor.value = '#00f' fontSize.value = 24 }, 2000) </script> ``` 通过响应式变量控制样式属性值Vue会自动更新DOM样式[^2] ### 二、类名动态绑定 ```vue <template> <div :class="{ 'active-box': isActive, 'error-state': hasError }">状态容器</div> </template> <script setup> import { ref } from 'vue' const isActive = ref(true) const hasError = ref(false) </script> <style> .active-box { border: 2px solid #4CAF50; background-color: #e8f5e9; } .error-state { box-shadow: 0 0 8px #ff5722; } </style> ``` 当`isActive`或`hasError`变化时,对应类名会自动更新[^3] ### 三、样式数组绑定 ```vue <template> <div :style="[baseStyles, overrideStyles]">组合样式示例</div> </template> <script setup> import { reactive } from 'vue' const baseStyles = reactive({ padding: '20px', borderRadius: '8px' }) const overrideStyles = reactive({ backgroundColor: '#fff3e0' }) </script> ``` ### 四、Composition API实现 ```vue <template> <button @click="toggleTheme" :style="themeStyle">切换主题</button> </template> <script setup> import { ref, computed } from 'vue' const isDark = ref(false) const themeStyle = computed(() => ({ backgroundColor: isDark.value ? '#2c3e50' : '#f0f0f0', color: isDark.value ? '#ecf0f1' : '#2c3e50' })) function toggleTheme() { isDark.value = !isDark.value } </script> ``` 使用计算属性实现响应式样式切换
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值