Get real width of elements with jQuery

前端 未结 6 1976
Happy的楠姐
Happy的楠姐 2021-02-12 16:48

I am writing a validator for \"visual correctness\" of html files. The goal is to detect too wide elements.

Here is a demo of my problem.

The do

6条回答
  •  一生所求
    2021-02-12 17:18

    This effect is called "shrinkwrapping", and there's a couple of ways to determine the "real" width of the element.

    Float

    One of the ways that you can use is to float your

    element which will force it as small as possible, but you'll need to use a clearfix if anything inside your div is floating:

    #two { float: left; }
    

    Inline-block element

    Inserting an inline element should work.

    content

    would become

    content

    Absolutely positioned element

    Changing the element position to be absolute should also work:

    #two { position: absolute; }
    

    If you can't statically change the markup or the style, you can always change them dynamically through JavaScript.

    (absolutely positioned element)

    var realWidth = $("#two").css("position", "absolute").width();
    

    (float)

    var realWidth = $("#two").css("float", "left").width();
    

    (inline-block element)

    var t = $("#two").html();
    var realWidth = $("#two")
        .empty()
        .append($("").html(t))
        .width();
    

提交回复
热议问题