jQuery innerWidth in Chrome with invisible elements
I am having an odd problem with jQuery 1.5.2 in Chrome.
I have code that looks like the following
$("img").each(function () {
if (this.complete) {
imageOnload.call(this);
} else {
$(this).bind("load", imageOnload);
}
});
function imageOnload () {
var $this = $(this);
foo($this);
}
function foo ($img) {
var width = $img.innerWidth();
var height = $img.innerHeight();
}
Keel in mind that this is really simplified for the question.
The above works great in most cases. The problem is that when $img(":visible") == false
, Chrome is returning 0 for innerWidth
and innerHeight
. I actually do need to take padding into account, hence the inner functions.
What is the best way to go about handling this situation? I am currently using
function foo ($img) {
var width;
var height;
if ($img.is(":visible")) {
width = $img.innerWidth();
height = $img.innerHeight();
} else {
var img = $img[0];
var pt = parseInt(img.style.paddingTop);
var pb = parseInt(img.style.paddingBottom);
var pl = parseInt(img.style.paddingLeft);
var pr = parseInt(img.style.paddingRight);
width = img.width + pl + pr;
height = img.height + pt + pb;
}
}
but I know this is rife with problems. I can't quite unravel how jQuery calculates individual padding, 开发者_如何学Pythonbut I suspect adapting that would improve the else section of my hack.
Is there a better solution or workaround to getting innerWidth
and innerHeight
when $img(":visible") == false
?
Thanks.
ADDENDUM:
As noted in a comment below, the solution is not as simple as making the image visible, calculating, and then hiding. If something in the parent chain is not visible, then the problem happens. In addition, a few things can trigger the problem.
Height and width calculate to zero in both Chrome and FireFox when the image or a descendent has display:none
. Chrome, but apparently not FireFox, also does when the image is masked off because a descendent has overflow:hidden
. I am going to try to see how this works in Safari later this weekend.
What about setting your image visible, take width/height and make your image invisible again? The user shouldn't even see it appear/disappear, unless your image is a 15mb shitload :).
Unless someone comes up with a better explanation of what is going on, or a better solution, I think this is the best way to handle the situation:
function foo ($img) {
var width;
var height;
if ($img.is(":visible")) {
width = $img.innerWidth();
height = $img.innerHeight();
} else {
var img = $img[0];
width = img.width;
height = img.height;
var style = null;
if (window.getComputedStyle) {
style = window.getComputedStyle(img, null);
} else if (img.currentStyle) {
style = img.currentStyle;
}
if (style) {
var pt = parseInt(style.paddingTop);
var pb = parseInt(style.paddingBottom);
var pl = parseInt(style.paddingLeft);
var pr = parseInt(style.paddingRight);
width += img.width + pl + pr;
height += img.height + pt + pb;
}
}
}
精彩评论