如何在页面底部但在(未固定)页脚上方制作固定的“转到顶部”按钮?

Posted

技术标签:

【中文标题】如何在页面底部但在(未固定)页脚上方制作固定的“转到顶部”按钮?【英文标题】:How to make a fixed "go to top" button on the page bottom, but above the (not fixed) footer? 【发布时间】:2018-08-26 00:22:30 【问题描述】:

我已经制作了一个页面(在 Shopify 上),并在左下角制作了一个固定的“转到顶部”箭头。没关系,但是当我滚动到页面底部时,箭头会在页脚前面,我希望它保持在页脚上方。

这是我使用的代码:

$(document).ready(function() 			
  $(window).scroll(function() 
    if ($(this).scrollTop() > 200) 
      $('.go-top').fadeIn(200);
     else 
      $('.go-top').fadeOut(200);
    
  );

  $('.go-top').click(function(event) 
    event.preventDefault();

    $('html, body').animate(scrollTop: 0, 300);
  )
);
.go-top 
  position: fixed;
  bottom: 2em;
  right: 0.5em;
  text-decoration: none;
  font-size: 40px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="go-top"> &#x2191; </a>

【问题讨论】:

玩转 z-index 设置windows监听,当页面到达页面底部时,根据页面位置改变bottom属性 @ScottMarcus 我不认为将他的代码更改为 sn-p 是件好事,因为没有什么可工作的......我认为代码 sn-p 对于任何代码都不应该是自动的,它应该只对我们可以看到行为的完整工作代码是强制性的 把$('a.go-top') 作为footer 的一个子级怎么样? @TemaniAfif 使用代码 sn-p 是一个好主意,原因有以下三个。 1)我们现在可以运行代码并可视化 OP 制作的 UI(正在运行)2)如果存在可能 OP 没有发现的语法错误,我们可以立即看到 3)现在任何人都可以单击“复制” sn-p to answer”并创建一个完全运行的解决方案。一般来说,使用代码 sn-p 的原因并不多。 【参考方案1】:

将 z-index 添加到 css。 类似:

z-index: 100000

使数字尽可能大,使其位于顶部。

【讨论】:

虽然这是正确的方向,但我建议使用尽可能低的值来实现所需的结果,以防止 z-index 噩梦。考虑想要一个弹出/弹出模式,你可能想要它下面的“回到顶部”。【参考方案2】:

    $(document).ready(function() 		
      $(window).scroll(function() 
   //--------------------------- Lines added ------------------------//
       var footertotop = ($('.footer').position().top);
       var scrolltop = $(document).scrollTop() + window.innerHeight;
       var difference = scrolltop-footertotop;
      if (scrolltop > footertotop) 
        $('.go-top').css('bottom' : difference);
      else
        $('.go-top').css('bottom' : 10);
      ;   
  //--------------------------- end ---------------------------------//
      if ($(this).scrollTop() > 200) 
          $('.go-top').fadeIn(200);
       else 
          $('.go-top').fadeOut(200);
      
      );
      $('.go-top').click(function(event) 
        event.preventDefault();
        $('html, body').animate(scrollTop: 0, 300);
      )
    );
.containerheight:2000px;position:relative
.footerheight:200px;width:100%;position:absolute;bottom:0px;background:red

.go-top 
  position: fixed;
  bottom: 20px;
  display:none; // <---- Dont display on page load
  right: 0.5em;
  text-decoration: none;
  font-size: 40px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
<a href="#" class="go-top"> &#x2191; </a>
<div class="footer"></div>
</div>

【讨论】:

以上是关于如何在页面底部但在(未固定)页脚上方制作固定的“转到顶部”按钮?的主要内容,如果未能解决你的问题,请参考以下文章

如何将页脚固定在页面底部

访问报告:页面底部的可变高度文本

将页脚固定到页面底部

如何使页脚固定在页面底部

页脚总是在底部不显示:固定

仅在滚动到底部时将页脚固定到底部