Why does jQuery.css('width') return different values in different browsers?

前端 未结 2 1977
一个人的身影
一个人的身影 2021-01-19 14:40

I\'ve written some jQuery code that reads the width of the columns in a table and applies them to another table.

On my page, there is a TABLE like this:



        
相关标签:
2条回答
  • 2021-01-19 15:04

    JQuery normalizes browser handling in this situation via $().width().

    css("width") is a different attribute / property that is not normalized but instead it retrieves the CSS value for the element(s). width() is the "actual size in the dom" but doesn't take padding and margins where applicable into consideration where css("width") only retrieves the CSS value. As others have mentioned below this answer, .outerWidth() will do what .width() accomplishes, but includes padding and margins as represented by the native browser.

    In short:

    $(this).width() != $(this).css("width")
    

    A good parallel example is this:

    $(this).css("width")
    

    is closer to

    $(this).attr("name")
    

    than $(this).width() or $(this).height().

    Edit:

    Here is something I just tabbed over and saw that also illustrates the difference:

    $(this).css("height", "auto");
    alert($(this).height());
    

    The alert will be a numeric value (pixels).

    0 讨论(0)
  • 2021-01-19 15:23

    I faced the same problem trying to detect the width of the body and load specific scripts and I worked around it this way. May help you as well.

    $('body,html').css({'overflow':'hidden'});
    var width = $('body').width();
    $('body,html').css({'overflow':''});
    

    this gives a consistent value in all major browsers

    `

    0 讨论(0)
提交回复
热议问题