Get real width of elements with jQuery

前端 未结 6 1978
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

    As others have pointed out, changing the position of the element to absolute also works. Doing this will result in an inline-style which can mess with your css afterwards if you don't watch out. Here is a solution to get rid of the inline style again.

    //Change position to absolute
    $('#two').css("position", "absolute");
    var textWidth = $('#two').width();
    
    //Get rid of the inline style again
    $('#two').removeStyle("position");
    
    
    
    //Plugin format
    (function ($) {
        $.fn.removeStyle = function (style) {
            var search = new RegExp(style + '[^;]+;?', 'g');
    
            return this.each(function () {
                $(this).attr('style', function (i, style) {
                    return style.replace(search, '');
                });
            });
        };
    }(jQuery));
    

提交回复
热议问题