DOM Element Width before Appended to DOM

后端 未结 6 1728
渐次进展
渐次进展 2020-12-09 02:27

I\'m sure the answer is no, but is it possible to determine the width of an element before it is appended to the DOM?

Once it\'s appended, I know I

6条回答
  •  孤城傲影
    2020-12-09 03:08

    Modified the code a bit. Here is a pure JS solution:

    function measure(el, fn) {
        var pV = el.style.visibility, 
            pP = el.style.position;
            
        el.style.visibility = 'hidden';
        el.style.position = 'absolute';
        
        document.body.appendChild(el);
        var result = fn(el);
        el.parentNode.removeChild(el);
        
        el.style.visibility = pV;
        el.style.position = pP;
        return result;
    }
    
    var div = document.createElement('div');
    div.innerHTML = "

    Hello


    "; alert(div.offsetHeight); // 0 alert(measure(div, function(el){return el.offsetHeight})); // 68

提交回复
热议问题