You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VueJS 2.5替代jQuery获取元素line-height样式值的方法

在Vue 2.5中获取元素的line-height值

嘿,很高兴帮你搞定这个问题!其实Vue里完全可以用原生JS的方法实现,和jQuery底层逻辑是一致的,完全不用依赖jQuery~

核心思路:用window.getComputedStyle()获取计算后样式

jQuery的css()方法在现代浏览器里本质就是靠getComputedStyle来获取最终渲染的样式值,所以我们直接用这个原生API就行。

适配你现有代码的解决方案

如果要获取当前组件根元素(也就是this.$el对应的元素)的line-height,直接在mounted钩子中这么写:

data: function () {
  return {
    lineHeight: null
  }
},
mounted(){
  // 获取根元素计算后的line-height值
  this.lineHeight = window.getComputedStyle(this.$el).lineHeight;
}

如果要获取组件内特定元素的line-height

要是你需要的不是根元素的样式,而是组件里某个特定DOM元素的line-height,记得先给目标元素加上ref标识:

<template>
  <div>
    <p ref="targetText">这是要获取样式的文本段落</p>
  </div>
</template>

然后在mounted里通过$refs拿到元素再计算样式:

mounted(){
  const targetElement = this.$refs.targetText;
  this.lineHeight = window.getComputedStyle(targetElement).lineHeight;
}

额外小提醒

  • getComputedStyle返回的是带单位的字符串(比如"24px"),如果需要纯数值,可以用parseInt(this.lineHeight, 10)或者parseFloat(this.lineHeight)转换。
  • 必须在mounted钩子中执行这段代码,因为此时组件已经挂载到DOM上了;created钩子阶段元素还没渲染,根本拿不到样式。

内容的提问来源于stack exchange,提问作者lucasumberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:30:39