weixin_50802888 2022-05-26 10:55 采纳率: 63.3%
浏览 98
已结题

元素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.
  • 写回答

1条回答 默认 最新

  • 你好!机器人 2022-05-26 11:28
    关注

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

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 6月3日
  • 创建了问题 5月26日

悬赏问题

  • ¥15 ue2.6.12版本用的若以,安装gojs,引入import * as go from 'gojs';报错
  • ¥15 服务器上的网站安装php5.6版本
  • ¥15 ModuleNotFoundError: No module named 'torch.utils._import_utils' 是缺少什么
  • ¥15 请大咖一起探索iptv 直播源的hls通过反向代理解密
  • ¥100 寻找技术员 云闪付tn转h5输入卡号付款的链接 重酬!
  • ¥100 科大讯飞语音唤醒词,unbuntu环境,报错
  • ¥50 python写segy数据时出错2
  • ¥20 关于R studio 做精确稳定检验的问题!(语言-r语言)
  • ¥50 用贝叶斯决策方法,设计CAD程序
  • ¥20 关于#目标检测#的问题:(qq收集表到时间才能填写,填写的份数有上限)