【问题标题】:The offsetWidth, scrollWidth,ClientWidth Property is not working for Html ElementoffsetWidth、scrollWidth、ClientWidth 属性不适用于 Html 元素
【发布时间】:2015-01-09 07:44:14
【问题描述】:

我有这个控件并试图获取 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>

我的代码..

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

alert("offset Width =" +a);
alert("client Width =" +b);
alert("scroll Width =" +c);

警报消息显示为“未定义” 我在 Chrome 和 IE11 中都试过,结果都一样。

【问题讨论】:

  • 尝试记录这些变量以确保您首先在其中包含某些内容。
  • 变量是被创建的,所以之前不可能有值
  • 您正在混合使用 javascript 和 jquery。例如,offsetWidth 用于 js 对象,而您正尝试在 jquery 对象上使用它

标签: javascript jquery html dom


【解决方案1】:

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

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

现在你已经将元素本身存储在 var tid 中(这比写三遍 $("#tid") 更好)并且可以这样做:

var a = tid.offsetWidth;
var b = tid.clientWidth;
var c = tid.scrollWidth;

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

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

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

【讨论】:

  • 在 chrome 中,如果你的元素是内联显示的,那么它将返回 0。请查看jsfiddle.net/w4k0rnpo/1 进行验证
  • IE 11 所有三个属性都返回值为 offsetWidth =242, scrollWidth=540 但在 Chrome 中 offsetWidth 返回为 242,scrollWidth 为 0
  • @Gowthaman 我已经更新了我的答案。在您的情况下,最好的解决方案是 CSS#tid {display: inline-block;}.
猜你喜欢
  • 2021-01-26
  • 2014-01-30
  • 2017-06-19
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多