e.offsetWidth返回错误的值

时间:2016-08-31 12:46:20

标签: javascript html css

在我的应用程序中,我想检查是否存在文本溢出(省略号)。为此,我检查e.offsetWidth < e.scrollWidth但它们返回相等的值,表示offsetWidth返回错误的值。这是我的实现:

CSS

.less{
  display: block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.complete{
  word-wrap: break-word;
}

.collapse{
  color:blue;
  font-size:13px;
  cursor:pointer;
}

.hideElement{
 display: none;
}

#seemore:after{
  content: " \000BB";
}
#seeless:before{
   content:"\000AB\ ";
}

#description {
  width: 100%;
  overflow: hidden;
}

HTML

<div id = "description">
    <div id="lessdescription" class="less"></div>
    <div id="seemore" class="collapse"></div>
    <div id="seeless" class="collapse hideElement"></div>
</div>

JS

function manageReportDescription() {
    var descriptionElement = document.getElementById("lessdescription");

    return descriptionElement.offsetWidth < descriptionElement.scrollWidth;
}   
  

我想使用纯JS属性(不依赖于jQuery)

1 个答案:

答案 0 :(得分:0)

您的Javascript代码没问题,问题是因为div中没有文字,因此offsetWidth等于屏幕宽度,scrollWidth也等于屏幕宽度,所以比较将返回false,因为比较的两个元素具有相同的值屏幕宽度,请尝试在lessdescription div中添加一些文字

When adding some text to the <code>div</code> the values change, and it return <code>true</code>