元素offsetWidth问题

元素offsetWidth问题

<template>
  <el-tooltip
    :content="str"
    :disabled="isShowTooltip"
    effect="dark"
    placement="top"
  >
    <div
      style="overflow: hidden;  text-overflow: ellipsis; white-space: nowrap;"
      @mouseover="onMouseOver(str)"
    >
      <span :ref="str">{{ str }}</span>
    </div>
  </el-tooltip>
</template>
export default {
  data() {
    return {
      isShowTooltip: false,
      str: 'sddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'
    }
  },
  methods: {
    onMouseOver(str) { // 内容超出,显示文字提示内容
      const tag = this.$refs
      console.log('tag============>', tag)
      const parentWidth = tag.parentNode.offsetWidth // 获取元素父级可视宽度
      const contentWidth = tag.width // 获取元素可视宽度
      console.log('parentWidth============>', parentWidth)
      console.log('contentWidth============>', contentWidth)
      this.isShowTooltip = contentWidth <= parentWidth
    }
  }
}

我的疑问是:

  1. this.$refs[str]拿到的元素,为什么没有width属性,只有offsetWidth属性,二者有什么不同
  2. 假设屏幕可视宽度是900px,文本真实宽度是1000px,由于设置了文本换行隐藏。所以看到的文本是末尾带省略号的。可为什么这时候打印span的offsetWidth,依旧是1000px,offsetWidth不是可视宽度吗,按理说应该是900.

如果是内嵌样式 style="width:100px,height:100px;
this.$refs[str].style.width 这可以取到宽度
如果非内嵌样式,即样式写在样式表里面:
只能通过以下方式获取宽高:
this.$refs.ele.offsetWidth
两者区别
width:获取的元素宽度是元素的宽度,不包括border、和padding所占的宽度,且宽度值是带单位px的。
offsetWidth 获取的元素宽度为width+border+padding的值(不包括margin),且返回值只为一个数值,不带单位。