vue 获取dom的css属性值

本文介绍在Vue.js中如何使用ref属性获取DOM元素如div和img的高度、宽度及图片源路径。通过mounted生命周期钩子函数,演示了如何访问和打印这些样式属性。
<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>嗯,用户想了解在Vue获取元素style属性值的方法。结合之前的对话历史和系统指令,我需要给出清晰可靠的中文解答。 用户引用了两篇资料:第一篇详细说明了使用mounted钩子和$refs获取内联样式的方法;第二篇提到了jQuery方式获取自定义属性,但不太符合Vue的最佳实践。用户明确聚焦在style属性值获取上。 考虑设计分层次的解决方案:首先是最常用的内联样式获取(通过refs),然后是计算样式的获取(需要window.getComputedStyle),最后提醒注意事项。这样既覆盖基础场景又满足复杂需求。 特别注意要区分内联样式和计算样式这两个关键概念:内联样式只能获取标签直接写入的样式,而计算样式能获取最终渲染生效的所有样式。这个区别对用户实际开发很重要。 需要强调响应式更新的问题:直接获取的样式值不会自动更新。如果用户需要动态追踪样式变化,可能要建议改用Vue的数据驱动方式或监听resize事件。 准备在最后补充几个相关问题:包括样式绑定、响应式监听等常见需求场景。这些问题既能帮助用户深化理解,也符合系统指令要求生成相关问题的要求。 </think>在Vue获取元素的style属性值有以下几种常用方法,根据需求选择合适方案: ### ✅ 方法一:通过`$refs`获取内联样式(推荐) ```vue <template> <!-- 添加ref标识元素 --> <div ref="targetElement" style="width: 100px; color: red">示例元素</div> </template> <script> export default { mounted() { // 获取DOM元素 const el = this.$refs.targetElement; // 获取具体样式值 const width = el.style.width; // "100px" const color = el.style.color; // "red" console.log("元素宽度:", width); } } </script> ``` > **适用场景**:获取标签内直接编写的`style`属性 > **注意**:仅能获取内联样式,无法获取CSS类定义的样式[^1] --- ### ✅ 方法二:获取计算样式(含CSS类样式) ```javascript mounted() { const el = this.$refs.targetElement; // 获取所有最终计算样式 const computedStyle = window.getComputedStyle(el); // 获取特定属性 const fontSize = computedStyle.getPropertyValue('font-size'); const marginTop = computedStyle.marginTop; console.log("实际字体大小:", fontSize); // 获取最终渲染值 } ``` > **核心API**:`window.getComputedStyle(element)` > **优势**:可获取所有最终生效的样式(包括CSS类、继承样式等) > **注意**:返回值为只读,不能直接修改[^1] --- ### ✅ 方法三:通过DOM API获取 ```javascript // 使用querySelector(需确保元素已渲染) mounted() { const el = document.querySelector('.custom-class'); const bgColor = el.style.backgroundColor; } ``` > **适用场景**:未使用ref标识的元素 > **注意**:在`mounted`或之后的生命周期操作,确保DOM已存在 --- ### ️ 重要注意事项 1. **时机问题**:必须在`mounted`或之后的生命周期钩子中操作 ```javascript mounted() { /* 正确时机 */ } created() { /* 此时DOM未生成 */ } ``` 2. **响应式限制**:直接获取的样式值不会自动更新,需监听尺寸变化时可用`ResizeObserver` 3. **样式优先级**:`element.style`仅返回内联样式,`getComputedStyle`返回最终计算值 > **最佳实践**:若需动态修改样式,推荐使用Vue的响应式绑定: ```vue <template> <div :style="{ width: dynamicWidth }"></div> </template> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值