Get real width of elements with jQuery

前端 未结 6 1999
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条回答
  •  猫巷女王i
    2021-02-12 17:27

    As others have said, temporarily wrap the text node in an inline element.

    var two = document.getElementById('two'),
        text = two.firstChild,
        wrapper = document.createElement('span');
    
    // wrap it up
    wrapper.appendChild(text);
    two.appendChild(wrapper);
    
    // better than bad, it's good.
    console.log(wrapper.offsetWidth);
    
    // put it back the way it was.
    two.removeChild(wrapper);
    two.appendChild(text);
    

    http://jsfiddle.net/vv68y/12/

    Here is a getInnerWidth function that should be useful to you. Pass it an element and it will handle the wrapping and unwrapping.

    function getInnerWidth(element) {
    
        var wrapper = document.createElement('span'),
            result;
    
        while (element.firstChild) {
            wrapper.appendChild(element.firstChild);
        }
    
        element.appendChild(wrapper);
    
        result = wrapper.offsetWidth;
    
        element.removeChild(wrapper);
    
        while (wrapper.firstChild) {
            element.appendChild(wrapper.firstChild);
        }
    
        return result;
    
    }
    

    http://jsfiddle.net/vv68y/13/

提交回复
热议问题