简体   繁体   中英

Javascript: How to keep track of absolute positions (top/left) of a div?

I need to get all the positions of a html element (div) based on its position on the screen. I'd like something like addEventListener that would send the element's positions whenever the screen changes (on resize/on zoom/on scrolling etc - whenever the position of an element changes). Is that possible with pure Javascript?

This is not intended to be a complete answer but two examples of what I meant in the comment. Perhaps it will be of some assistance in setting up what you are trying to do. There is not a pre-built method to do what you want but that doesn't mean you cannot do it.

The first one is used to adjust the screen layout if the user alters the browser's default font size. There is no event for that so I use the focus and blur events on the window and keep track of the size of an off-screen element in order to test whether the default font size changed. It is captured on blur and tested on focus . The resizing takes place in the sizeTable function.

window.addEventListener( 'focus', () => fontSizeProxy( false ), false );
window.addEventListener( 'blur', () => fontSizeProxy( true ), false );
fontSizeProxy.base = document.getElementById('sz_gauge').offsetHeight;
fontSizeProxy.size = document.querySelector('div.tabs').clientWidth;

function fontSizeProxy( b )
 {
   if ( b )
     { fontSizeProxy.size = document.querySelector('div.tabs').clientWidth; }
   else // focus event
     { setTimeout( done, 1000 ); };

    function done()
     {
       // Get w after the delay so browser can reset completely.
       let w = document.querySelector('div.tabs').clientWidth;
       if ( w !== fontSizeProxy.size )
         {
            fontSizeProxy.size = w;
            fontSizeProxy.base = document.getElementById('sz_gauge').offsetHeight;
            sizeTable( nav.n );
         }; // end if
       w = null;    
    } // close done
 } // close fontSizeProxy

The second example is a resize event and is shown because it throttles the event so that the function sizeTable doesn't execute as often as the event fires. You may want less of a throttle than the 500ms used here.

window.addEventListener( 'resize', resize, false );

function resize()
 { 
    if ( !resize.clear ) 
      {
        resize.clear = setTimeout( () => { resize.clear = null; sizeTable( nav.n ); }, 500 );    
      }; // end if
 } // close resize

The concept for what you want is here, I think. You just need to make your version of a sizeTable function that queries and adjusts what you want to execute when the events take place and you may have to listen for numerous events to execute the same function, as done here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM