【问题标题】: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 的原因并不多。

标签: javascript html css footer fixed


【解决方案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);
      })
    });
.container{height:2000px;position:relative}
.footer{height: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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2015-08-26
    • 2013-09-25
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多