如何防止固定按钮重叠页脚区域,并将按钮停止在页脚所在的顶部

How to prevent fixed button from overlapping footer area and stop the button on top of where the footer is located

本文关键字:按钮 顶部 区域 何防止 重叠      更新时间:2023-09-26

我正在尝试创建一个固定在屏幕左下侧的按钮。我试着在JSFiddle中进行设置,以重新创建我想要做的事情。

这是我的HTML:

<div id="header">header
</div>
<div id="button">button
</div>
<div id="content">some content
</div>
<div id="footer">footer
</div>

和CSS:

#header,#footer{
background-color:red;

}
#content
{
    height:2000px;
}
#footer
{
    height:200px;
}
#button
{
    background-color:gray;
    width:100px;
    height:100px;
    position:fixed;
    bottom:0;
    left:0;
    right:0;    
}

我读过,我应该使用scrolltoFixed.js、lockfixed.js等插件但我的问题是,我不知道如何使用javascript,甚至不知道从哪里开始编辑javascript。这是一把小提琴

我希望按钮停止在页脚所在的位置,并使其看起来像是停靠的。

现在进行了更新,使其位于页脚上方。

希望这就是你的意思jQuery:

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
       $('#button').addClass('fixed_button');
   }else{
       $('#button').removeClass('fixed_button');
   }
});

CSS:

.fixed_button{
    position:absolute !important;
    margin-top:1900px;
    bottom: auto !important;
}

请改用绝对定位。另外,不要使用左:0和右:0。只使用其中一个。尝试

position:absolute;
bottom:0;
left:0;

编辑:抱歉,您的代码似乎可以工作。你到底想做什么?

我一直在寻找类似的东西,但找不到任何合适的答案。

var $fixed_element = $(".some_element")
if($fixed_element.length){
        var $offset = $(".footer").position().top,
            $wh = $(window).innerHeight(),
            $diff = $offset - $wh,
            $scrolled = $(window).scrollTop();
        $fixed_element.css("bottom", Math.max(0, $scrolled-$diff));
    }

所以现在固定元素会停在页脚之前。并且不会与之重叠。