jQuery - 使用锚链接将元素滚动到屏幕中间而不是顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18150090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Scroll element to the middle of the screen instead of to the top with an anchor link
提问by Nils Kaspersson
I'm building a one-page site with a fixed-positioned navigation bar which scrolls smoothly to the different section elements through anchor links. The default behaviour for scrolling to an element is to align it to the top of the browser window. Instead, I want to align the element to the middle of the screen.
我正在构建一个带有固定位置导航栏的单页网站,该导航栏通过锚链接平滑滚动到不同的部分元素。滚动到元素的默认行为是将其与浏览器窗口的顶部对齐。相反,我想将元素与屏幕中间对齐。
I use this markup for navigation:
我使用此标记进行导航:
<nav class="main-nav">
<a href="#top">Top</a>
<a href="#section-1">Section 1</a>
<a href="#section-2">Section 2</a>
<a href="#section-3">Section 3</a>
<a href="#section-4">Section 4</a>
<a href="#section-5">Section 5</a>
</nav>
I use kswedberg's jQuery Smooth Scroll pluginto smooth the scrolling. I initiate it like this:
我使用kswedberg 的 jQuery Smooth Scroll 插件来平滑滚动。我是这样启动的:
$('.main-nav a').smoothScroll({
offset: 0,
speed: 700
});
I want to set the offset to be ((window).height / 2) - (element height / 2)
so that it's vertically centered, but I need help to figure out how to execute it properly.
我想将偏移量设置为((window).height / 2) - (element height / 2)
垂直居中,但我需要帮助来弄清楚如何正确执行它。
I need it to:
我需要它:
- Get the height of the window and divide it by two
- Get the height of the element and divide it by two
- Subtract the former from the latter
- If possible, align it to the top as per default if the element is higher than the window
- 获取窗口的高度并将其除以二
- 获取元素的高度并将其除以二
- 从后者中减去前者
- 如果可能,如果元素高于窗口,则默认将其与顶部对齐
Since there are many anchor links I assume I either need to check the height of the element the anchor link that was clicked links to, or initiate smoothScroll for every anchor link.
由于有很多锚链接,我假设我要么需要检查被点击的锚链接的元素的高度,要么为每个锚链接启动平滑滚动。
Does anybody know how to do this?
有人知道怎么做这个吗?
采纳答案by Steven Lambert
The API provides a way to execute a smoothScrollnot bound to an element.
You'll want to execute this method inside an onclick event for the anchor tags so that you can have access to it's target. Then you can calculate what you need to to get to the desired position. Since offset
is now an absolute offset instead of a relative offset, you'll need to get the exact position to scroll to.
API 提供了一种执行未绑定到元素的smoothScroll的方法。您需要在锚标记的 onclick 事件中执行此方法,以便您可以访问它的目标。然后,您可以计算到达所需位置所需的条件。由于offset
现在是绝对偏移量而不是相对偏移量,因此您需要获得要滚动到的确切位置。
$('.main-nav a').on('click', function(e) {
var el = $( e.target.getAttribute('href') );
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
$.smoothScroll({ speed: 700 }, offset);
return false;
});
回答by Santiago Angel
Here's how to do it with plain JQuery using scrollTo()
以下是使用 scrollTo() 使用普通 JQuery 的方法
$('.main-nav a').on('click', function(e) {
var el = $( e.target.getAttribute('href') );
var elOffset = el.offset().top;
var elHeight = el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
var speed = 700;
$('html, body').animate({scrollTop:offset}, speed);
});
This is a combination of straker's code and code from this question: jQuery scrollTo - Center Div in Window Vertically
这是 straker 的代码和来自这个问题的代码的组合:jQuery scrollTo - Center Div in Window Vertically
回答by ameer nagvenkar
Here a sure shot way to do it
这是一个可靠的方法来做到这一点
var $window = $(window),
$element = $('.my-element'),
elementTop = $element.offset().top,
elementHeight = $element.height(),
viewportHeight = $window.height(),
scrollIt = elementTop - ((viewportHeight - elementHeight) / 2);
$window.scrollTop(scrollIt);
回答by Farida Anjum
This can be done with vanilla JS using scrollIntoView
:
这可以使用 vanilla JS 完成scrollIntoView
:
document.getElementById('myID').scrollIntoView({
behavior: 'auto',
block: 'center',
inline: 'center'
});
回答by Andy
Here's the solution I ended up using. It works great if you have a scrollable parent container that holds all the elements that need to be centered when clicked on.
这是我最终使用的解决方案。如果您有一个可滚动的父容器,其中包含单击时需要居中的所有元素,则效果很好。
Feel free to run the code snippet to see it in action!
随意运行代码片段以查看它的运行情况!
$('#main-nav a').on('click', function(e) {
var el = $(this), parentEl = $('#main-nav');
var elOffset = el.offset().top + parentEl.scrollTop();
var elHeight = el.height();
var parentHeight = parentEl.height();
var offset = elOffset - ((parentHeight - elHeight) / 2);
parentEl.animate({scrollTop:offset}, 700);
});
#main-nav {
height: 200px;
width: 200px;
outline: 1px solid red;
overflow: hidden;
}
#main-nav a {
height: 50px;
background: blue;
display: block;
margin-bottom: 5px;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav id="main-nav">
<a href="#top">Top</a>
<a href="#section-1">Section 1</a>
<a href="#section-2">Section 2</a>
<a href="#section-3">Section 3</a>
<a href="#section-4">Section 4</a>
<a href="#section-5">Section 5</a>
<a href="#section-6">Section 6</a>
<a href="#section-7">Section 7</a>
<a href="#section-8">Section 8</a>
<a href="#section-9">Section 9</a>
<a href="#section-10">Section 10</a>
</nav>