jQuery中元素的总宽度(包括填充和边框) [英] Total width of element (including padding and border) in jQuery

查看:116
本文介绍了jQuery中元素的总宽度(包括填充和边框)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与本主题一样,如何使用jQuery获取元素的总宽度,包括其边框和填充?我有jQuery Dimensions插件,并且在760px-wide上运行.width()10px padding DIV返回760.

As in the subject, how can one get the total width of an element, including its border and padding, using jQuery? I've got the jQuery dimensions plugin, and running .width() on my 760px-wide, 10px padding DIV returns 760.

也许我做错了什么,但是如果我的元素显示为780 pixels wide并且Firebug告诉我上面有10px padding,但是调用.width()仅给出760,我很难被看到

Perhaps I'm doing something wrong, but if my element manifests itself as 780 pixels wide and Firebug tells me that there's 10px padding on it, but calling .width() only gives 760, I'd be hard pressed to see how.

谢谢您的建议.

推荐答案

[更新]

最初的答案写在jQuery 1.3之前,而当时存在的函数本身不足以计算整个宽度.

The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.

现在,作为 JP 正确指出,jQuery具有 outerWidth

Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border and padding by default, and also the margin if the first argument of the function is true

[原始答案]

width方法不再需要dimensions插件,因为它已被添加到jQuery Core

The width method no longer requires the dimensions plugin, because it has been added to the jQuery Core

您需要做的是获取特定div的填充,边距和边框宽度值,并将它们添加到width方法的结果中

What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width method

类似这样的东西:

var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width

分成多行以提高可读性

这样,即使您从css更改了padding或margin值,也将始终获得正确的计算值

That way you will always get the correct computed value, even if you change the padding or margin values from the css

这篇关于jQuery中元素的总宽度(包括填充和边框)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆