Fixed position but relative to container

后端 未结 25 1603
独厮守ぢ
独厮守ぢ 2020-11-21 23:52

I am trying to fix a div so it always sticks to the top of the screen, using:

position: fixed;
top: 0px;
right: 0px;

However,

25条回答
  •  无人共我
    2020-11-22 00:46

    I did something like that awhile back. I was pretty new to JavaScript, so I'm sure you can do better, but here is a starting point:

    function fixxedtext() {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            if (document.body.offsetWidth > 960) {
                var width = document.body.offsetWidth - 960;
                width = width / 2;
                document.getElementById("side").style.marginRight = width + "px";
            }
            if (document.body.offsetWidth < 960) {
                var width = 960 - document.body.offsetWidth;
                document.getElementById("side").style.marginRight = "-" + width + "px";
            }
        }
        else {
            if (window.innerWidth > 960) {
                var width = window.innerWidth - 960;
                width = width / 2;
                document.getElementById("side").style.marginRight = width + "px";
            }
            if (window.innerWidth < 960) {
                var width = 960 - window.innerWidth;
                document.getElementById("side").style.marginRight = "-" + width + "px";
            }
        }
        window.setTimeout("fixxedtext()", 2500)
    }
    

    You will need to set your width, and then it gets the window width and changes the margin every few seconds. I know it is heavy, but it works.

提交回复
热议问题