从页面底部向上滚动到一个元素(Scroll up to an element from bottom of the page)

编程入门 行业动态 更新时间:2024-10-24 04:31:31
从页面底部向上滚动到一个元素(Scroll up to an element from bottom of the page)

我想滚动到距离页面底部大约300px的按钮。

因此,无论何时按下它,身体都应向上或向下滚动,以便按钮始终位于屏幕的底部。

我真的不确定如何在我的案例中使用常见的jquery animate :

$(".hamburger").click( function(event) { $('html, body').animate({ scrollTop: $(document).height() - x //need help here }, 400); }); });

任何建议都非常感谢。

I'd like to scroll to the button that is placed approx 300px from the bottom of the page.

So, anytime when it is pressed, the body should scroll up or down so that the button always gets at the bottom of the screen.

I'm really not sure how can I use common jquery animate for my case:

$(".hamburger").click( function(event) { $('html, body').animate({ scrollTop: $(document).height() - x //need help here }, 400); }); });

Any advice is highly appreciated.

最满意答案

找到按钮的底部位置(顶部位置+按钮高度)并从中减去视口高度以确定滚动点。

$('button').on('click',function() {
  var bt = $(this).offset().top,
      bh = $(this).outerHeight(),
      bb = bt + bh,
      vh = $(window).height(),
      sp = bb - vh;
  $('html, body').animate({
    scrollTop: sp
  }, 400);
}); 
  
*{margin:0;}
section {
  height: 200vh;
}
footer {
  height: 200vh;
} 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
</section>
<footer>
  <button>asdf</button>
</footer> 
  
 

Find the bottom position of the button (top position + button height) and subtract the viewport height from that to determine the scroll point.

$('button').on('click',function() {
  var bt = $(this).offset().top,
      bh = $(this).outerHeight(),
      bb = bt + bh,
      vh = $(window).height(),
      sp = bb - vh;
  $('html, body').animate({
    scrollTop: sp
  }, 400);
}); 
  
*{margin:0;}
section {
  height: 200vh;
}
footer {
  height: 200vh;
} 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
</section>
<footer>
  <button>asdf</button>
</footer> 
  
 

更多推荐

本文发布于:2023-07-28 01:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   页面   Scroll   page   bottom

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!