Find the “potential” width of a hidden element

前端 未结 10 1316
慢半拍i
慢半拍i 2020-12-03 09:31

I\'m currently extending the lavalamp plugin to work on dropdown menus but I\'ve encountered a small problem. I need to know the offsetWidth of an element that

相关标签:
10条回答
  • 2020-12-03 10:21

    thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.

    Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.

    0 讨论(0)
  • 2020-12-03 10:25

    Two options:

    1. position the element outside the viewport (ex: left:-10000px)
    2. use visibility: hidden or opacity: 0 instead of hide().

    Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...

    0 讨论(0)
  • 2020-12-03 10:27

    I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.

    flexibox example enter image description here

    I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.

    Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.

    $('[selector]').onVisibleChanged(function(e, isVisible)
    {
        var realWidth = $('[selector]').width();
        var realHeight = $('[selector]').height();
    
        // render or adjust something
    });
    

    For more information, Please visit at my project GitHub.

    https://github.com/Soul-Master/visible.event.js

    demo: http://jsbin.com/ETiGIre/7

    0 讨论(0)
  • 2020-12-03 10:28
     var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
     var width = parseInt($hiddenElement.outerWidth());
     $hiddenElement.remove();
    
    0 讨论(0)
提交回复
热议问题