简体   繁体   中英

jQuery.height() behaves differently in WebKit and Firefox when using box-sizing:border-box

I have a textarea with the following style applied:

textarea {
    -webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;
}

If I then run the following javascript/jquery code, my textarea's height gets cut in half using Safari(5.0.6) and Chrome(16.0.x):

$('textarea').each( function() {
    var $this = $(this);
    $this.height( $this.height() );
}

According to the jQuery docs for .height(), this is the expected behavior because .height() returns the content height (no padding, border), regardless of the box-sizing property, but .height( value ) sets the content size accounting for the box-sizing property. So if my textarea has content-height:17px and padding-height:15px, .height() will return 17px. Then, if I set .height(17) my textarea that used to be 32px high is now only 17px high.

My real-world application is using jQuery.fn.autoResize 1.14 ( https://github.com/padolsey/jQuery.fn.autoResize ) on textareas that have box-sizing applied. That code pulls a similar stunt to what I've described above.

It works fine in FireFox 10. (That is, FireFox accounts for box-sizing in a more symmetrical way when getting and setting height.)

My question is: Where is the bug, and where should I look for/propose a workaround? The jQuery.fn.autoResize plugin, the jQuery team, webkit, or FireFox?

The bug is in jQuery ( http://bugs.jquery.com/ticket/11004 ) that makes $(el).height() not account for the box-sizing property. The fix is scheduled to go out in v1.8, however in the mean time you can use $(el).outerHeight() to get the height of the box accounting for padding and border ( http://api.jquery.com/outerHeight/ ).

Bug in jQuery calculations.

Solution:

var height = $this.outerHeight() - Number($this.css('padding-top').split('px')[0]) - Number($this.css('padding-bottom').split('px')[0]); 

If you have borders - also calculate them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM