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