为什么使用jQuery' .width()
方法设置元素的宽度会自动为数字添加填充和边距并将其转入DOM中?此行为未在文档中描述,并且作为默认值没有意义。我必须自己获取边距和填充,并从我想要的数字中减去,以使此方法按预期工作。
当你问jQuery什么是元素的宽度时它会删除填充和边距,它只是添加了你的想法,并报告一个错误的数字......不确定它是否总是表现得像这样或最近改变了。
$("#cowboy-btn").width(110); // results in 128px in the DOM instead of 110px
//$("#cowboy-btn").width("110px"); // same result 128px instead of 110px
console.log($("#cowboy-btn").width()); // reports 110, but its NOT, its 128!!!!
console.log($("#cowboy-btn").css("width")); // finally some sanity with 128px

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- the width in the DOM should be 110px, NOT 128px.. -->
<button id="cowboy-btn">Howdy partna!</button>
&#13;
答案 0 :(得分:-2)
$("#cowboy-btn").width(110); // results in 128px in the DOM instead of 110px
//$("#cowboy-btn").width("110px"); // same result 128px instead of 110px
console.log($("#cowboy-btn").outerWidth(true)); // reports 110, but its NOT, its 128!!!!
console.log($("#cowboy-btn").css("width")); // finally some sanity with 128px
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- the width in the DOM should be 110px, NOT 128px.. -->
<button id="cowboy-btn">Howdy partna!</button>
&#13;