与主题中一样,如何使用jQuery获取元素的总宽度,包括其边框和填充?我有一个jQuery dimensions插件,在我的760px-wide
上运行.width()
,10px padding
DIV返回760
。
也许我做错了什么,但是如果我的元素显示为780 pixels wide
,Firebug告诉我上面有10px padding
,但调用.width()
只得到760,我很难理解如何实现。
谢谢你的建议。
发布于 2011-04-09 11:10:33
看起来outerWidth在最新版本的jquery中被破坏了。
在以下情况下会出现差异
外部div是浮动的,内部div具有设置的宽度(小于外部div),内部div具有style=“style=:auto”
发布于 2012-09-27 05:22:02
为了简单起见,我将Andreas Grech的答案封装在一些函数中。对于那些想要一点剪切和粘贴快乐的人。
function getTotalWidthOfObject(object) {
if(object == null || object.length == 0) {
return 0;
}
var value = object.width();
value += parseInt(object.css("padding-left"), 10) + parseInt(object.css("padding-right"), 10); //Total Padding Width
value += parseInt(object.css("margin-left"), 10) + parseInt(object.css("margin-right"), 10); //Total Margin Width
value += parseInt(object.css("borderLeftWidth"), 10) + parseInt(object.css("borderRightWidth"), 10); //Total Border Width
return value;
}
function getTotalHeightOfObject(object) {
if(object == null || object.length == 0) {
return 0;
}
var value = object.height();
value += parseInt(object.css("padding-top"), 10) + parseInt(object.css("padding-bottom"), 10); //Total Padding Width
value += parseInt(object.css("margin-top"), 10) + parseInt(object.css("margin-bottom"), 10); //Total Margin Width
value += parseInt(object.css("borderTopWidth"), 10) + parseInt(object.css("borderBottomWidth"), 10); //Total Border Width
return value;
}
发布于 2011-08-19 00:41:52
同样的浏览器可能会返回边框宽度的字符串,在此parseInt中将返回NaN,因此请确保将值正确解析为int。
var getInt = function (string) {
if (typeof string == "undefined" || string == "")
return 0;
var tempInt = parseInt(string);
if (!(tempInt <= 0 || tempInt > 0))
return 0;
return tempInt;
}
var liWidth = $(this).width();
liWidth += getInt($(this).css("padding-left"));
liWidth += getInt($(this).css("padding-right"));
liWidth += getInt($(this).css("border-left-width"));
liWidth += getInt($(this).css("border-right-width"));
https://stackoverflow.com/questions/349705
复制相似问题