简体   繁体   中英

Updating (style.top) position of a floating menu with Javascript

I'm doing a floating menu with JavaScript, is suppose to stay in the same position no mater if the user scrolls down or resize the window.

So far it is working just fine with X position. However, I can't find a way to make it stick to a position relative to the visible top of the window. The problem is when I scroll down the menu disappear because it keeps its distance related to the window size.

my code is:

    menuPosition : function (){
        var windowHeight = document.body.clientHeight;
        var windowWidth = document.body.clientWidth;
        var xPosFloatingMenu = (windowWidth) - (fMenuWidthGlobal + fMenuXPosGlobal);
        var yPosFloatingMenu = (windowHeight) - (windowHeight - fMenuYPosGlobal);
        document.getElementById("floating_menu").style.left = (xPosFloatingMenu) + "px";
        document.getElementById("floating_menu").style.top = (yPosFloatingMenu) + "px";


    },

    updateMenuPosition : function () {
        var menuPositionInterval = setInterval(gala.create.menuPosition,1);
    } 

Is there a way to keep the menu position update relative to the visible top of the window?

You have to update the style properties of your floating_menu element on the window scroll Event .

https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll

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