【问题标题】:Scroll up to an element from bottom of the page从页面底部向上滚动到一个元素
【发布时间】:2017-01-21 20:05:08
【问题描述】:
我想滚动到距离页面底部约 300 像素的按钮。
因此,无论何时按下它,主体都应向上或向下滚动,以便按钮始终位于屏幕底部。
我真的不确定如何在我的情况下使用常见的jquery animate:
$(".hamburger").click( function(event) {
$('html, body').animate({
scrollTop: $(document).height() - x //need help here
}, 400);
});
});
非常感谢任何建议。
【问题讨论】:
标签:
javascript
jquery
html
css
jquery-animate
【解决方案1】:
找到按钮的底部位置(顶部位置 + 按钮高度)并从中减去视口高度以确定滚动点。
$('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>
【解决方案2】:
试试这个
HTML:
<div class="container"></div>
<a href="#" class="back">Back to top</a>
</div>
CSS:
.container {
background: cyan;
height: 800px;
}
JS:
$('a.back').click(function() {
$('html, body').animate({
scrollTop: 0
}, 700);
return false;
});