offsetWidth、scrollWidth、ClientWidth 属性不适用于 Html 元素

Gow*_*man 3 html javascript jquery dom

我有这个控件并试图获得 offsetWidth、clientWidth 和 scrollWidth..

<span class="label-block" style="height: 19px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">
<label for="ctl00_Form_PlaceHolder_chkIsAnnualSelfInsuranceRenewalCertificaterequired" id="tid" style="background-color:Transparent;">
Annual Self Insurance Renewal Certificate Required
</label>
 </span>
Run Code Online (Sandbox Code Playgroud)

我的代码..

var a=$("#tid").offsetWidth;
var b=$("#tid").clientWidth;
var c=$("#tid").scrollWidth;

alert("offset Width =" +a);
alert("client Width =" +b);
alert("scroll Width =" +c);
Run Code Online (Sandbox Code Playgroud)

我在 Chrome 和 IE11 中尝试过的警报消息显示为“未定义”,结果相同。

Mar*_*nst 5

$("#tid")将返回一个 jQuery 对象(其中包含 DOM-label-element),但这三个width是 DOM 元素本身的属性。所以你必须得到元素本身:

var tid = $("#tid").get(0); // or:
var tid = $("#tid")[0]; // or with native javascript:
var tid = document.getElementById("tid");
Run Code Online (Sandbox Code Playgroud)

现在您将元素本身存储在 var tid 中(这比写入三遍 $("#tid") 更好)并且可以执行以下操作:

var a = tid.offsetWidth;
var b = tid.clientWidth;
var c = tid.scrollWidth;
Run Code Online (Sandbox Code Playgroud)

根据评论:这些 jQuery 方法也适用于 Chrome 当元素为 display: inline;

var $tid = $("#tid"); // for jQuery-methods we need the jQuery-object

var e = $tid.outerWidth(); // corresponds to offsetWidth
var f = $tid.innerWidth(); // corresponds to clientWidth
Run Code Online (Sandbox Code Playgroud)

由于 jQuery 没有 element.scrollWidth 的直接等效项,并且 inline-elements 没有给出可靠的值,scrollWidth因此最好将它们设置为display: inline-block;.