I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section.
我的页面上有几个超链接。一个FAQ,用户在访问我的帮助部分时会看到。
Using Anchor links, I can make the page scroll towards the anchor and guide the users there.
使用锚点链接,我可以使页面向锚点滚动,并在那里引导用户。
Is there a way to make that scrolling smooth?
有没有一种方法可以使滚动平滑?
But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?
但是请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的东西?
20 个解决方案
#1
886
Update April 2018: There's now a native way to do this:
更新2018年4月:现在有一个本地的方法:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
This is currently only supported in the most bleeding edge browsers.
这目前只在最糟糕的边缘浏览器中支持。
For older browser support, you can use this jQuery technique:
对于旧的浏览器支持,您可以使用jQuery技术:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
And here's the fiddle: http://jsfiddle.net/9SDLw/
这是小提琴:http://jsfiddle.net/9SDLw/
If your target element does not have an ID, and you're linking to it by its name
, use this:
如果您的目标元素没有ID,并且您通过它的名称链接到它,请使用以下方法:
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
For increased performance, you should cache that $('html, body')
selector, so that it doesn't run every single time an anchor is clicked:
为了提高性能,您应该缓存$('html, body')选择器,这样它就不会在每次单击锚点时运行:
var $root = $('html, body');
$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
If you want the URL to be updated, do it within the animate
callback:
如果要更新URL,请在动态回调中进行:
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
#2
146
The correct syntax is:
正确的语法是:
//Smooth scrolling with links
$('a[href*=\\#]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
$('html,body').animate({scrollTop:$(location.hash).offset().top}, 500);
});
Simplifying: DRY
简化:干
function smoothScrollingTo(target){
$('html,body').animate({scrollTop:$(target).offset().top}, 500);
}
$('a[href*=\\#]').on('click', function(event){
event.preventDefault();
smoothScrollingTo(this.hash);
});
$(document).ready(function(){
smoothScrollingTo(location.hash);
});
Explanation of href*=\\#
:
解释href * = \ \ #:
-
*
means it matches what contains#
char. Thus only match anchors. For more about the meaning of this, see here - *表示它匹配包含# char的内容。因此只匹配定位。更多关于这个的意义,请看这里
-
\\
is because the#
is a special char in css selector, so we have to escape it. - \是因为#是css选择器中的一个特殊字符,所以我们必须转义它。
#3
20
$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});
this worked perfect for me
这对我来说是完美的
#4
8
I suggest you to make this generic code :
我建议你制定这个通用代码:
$('a[href^="#"]').click(function(){
var the_id = $(this).attr("href");
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;});
You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide
您可以在这里看到一篇非常好的文章:jquery- effth - scroll-defiled
#5
5
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Official: http://css-tricks.com/snippets/jquery/smooth-scrolling/
官方:http://css-tricks.com/snippets/jquery/smooth-scrolling/
#6
4
Using JQuery:
使用JQuery:
$('a[href*=#]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
#7
2
Adding this:
添加:
function () {
window.location.hash = href;
}
is somehow nullifying the vertical offset
是否取消了垂直偏移量
top - 72
in Firefox and IE, ut not in Chrome. Basically, the page scrolls smoothly to the point at which it should stop based upon the offset, but then jumps down to where the page would go without the offset.
在Firefox和IE中,ut不是在Chrome中。基本上,页面平滑地滚动到基于偏移量应该停止的位置,然后跳转到页面没有偏移量的位置。
It does add the hash to the end of the url, but pressing back does not take you back to the top, it just removes the hash from the url and leaves the viewing window where it sits.
它确实将散列添加到url的末尾,但是按下back并不会将您带回到顶部,它只是从url中删除散列,并将查看窗口留在它所在的位置。
Here is the full js I am using:
这里是我使用的全部js:
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top - 120
}, 500, function () {
window.location.hash = href;
});
return false;
});
#8
2
This solution will also work for the following URLs, without breaking anchor links to different pages.
此解决方案也适用于以下url,而不会中断指向不同页面的锚定链接。
http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor
./index.html
./index.html#anchor
etc.
等。
var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});
I haven't tested this in all browsers, yet.
我还没有在所有浏览器中进行测试。
#9
2
This will make it easy to allow jQuery to discern your target hash and know when and where to stop.
这将使jQuery更容易识别目标散列,并知道何时何地停止。
$('a[href*="#"]').click(function(e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
#10
2
The answer given works but disables outgoing links. Below a version with an added bonus ease out (swing) and respects outgoing links.
给出的答案是有效的,但是禁止输出链接。下面的版本增加了额外的额外好处,可以轻松退出(swing)并尊重传出的链接。
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
#11
2
HTML
HTML
<a href="#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
or With absolute Full URL
或者使用绝对完整的URL
<a href="https://somewebsite.com/#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
jQuery
jQuery
$j(function() {
$j('a.smooth-scroll').click(function() {
if (
window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& window.location.hostname == this.hostname
) {
var target = $j(this.hash);
target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$j('html,body').animate({
scrollTop: target.offset().top - 70
}, 1000);
return false;
}
}
});
});
#12
2
Modern browsers are a little faster these days. A setInterval might work. This function work well in Chrome and Firefox these days.(A little slow in safari, didn't bother with IE)
现在的浏览器快了一点。setInterval可能工作。这个功能目前在Chrome和Firefox中运行良好。(safari有点慢,不用IE)
function smoothScroll(event) {
if (event.target.hash !== '') { //Check if tag is an anchor
event.preventDefault()
const hash = event.target.hash.replace("#", "")
const link = document.getElementsByName(hash)
//Find the where you want to scroll
const position = link[0].getBoundingClientRect().y
let top = 0
let smooth = setInterval(() => {
let leftover = position - top
if (top === position) {
clearInterval(smooth)
}
else if(position > top && leftover < 10) {
top += leftover
window.scrollTo(0, top)
}
else if(position > (top - 10)) {
top += 10
window.scrollTo(0, top)
}
}, 6)//6 milliseconds is the faster chrome runs setInterval
}
}
#13
1
Here is the solution I implemented for multiple links and anchors, for a smooth scroll:
下面是我为多个链接和锚点实现的一个平滑滚动的解决方案:
http://www.adriantomic.se/development/jquery-localscroll-tutorial/ if you have your navigation links set up in a navigation div and declared with this structure:
http://www.adriantomic.se/development/jquer-localscroll-tutorial/如果您的导航链接设置在一个导航div中,并使用以下结构声明:
<a href = "#destinationA">
and your corresponding anchor tag destinations as so:
以及相应的锚标记目的地:
<a id = "destinationA">
Then just load this into the head of the document:
然后将其加载到文档的头部:
<!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>
<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>
<script type = "text/javascript">
$(document).ready(function()
{
// Scroll the whole document
$('#menuBox').localScroll({
target:'#content'
});
});
</script>
Thanks to @Adriantomic
由于@Adriantomic
#14
1
If you have a simple button on the page to scroll down to a div and want the back button to work by jumping to top, just add this code:
如果你在页面上有一个简单的按钮向下滚动到一个div,并且想要后退按钮通过跳转到顶部来工作,只需添加以下代码:
$(window).on('hashchange', function(event) {
if (event.target.location.hash=="") {
window.scrollTo(0,0);
}
});
This could be extended to jump to different divs too, by reading the hash value, and scrolling like Joseph Silbers answer.
这也可以扩展为跳转到不同的div,通过读取散列值,并像Joseph Silbers一样滚动。
#15
1
Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;
不要忘记offset()函数将元素的位置赋给文档。所以当你需要滚动你的元素相对于它的父元素你应该使用它;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.
关键是获取scroll-div的scrollTop并将其添加到scrollTop。如果不这样做,position()函数总是会给出不同的位置值。
#16
1
$("a").on("click", function(event){
//check the value of this.hash
if(this.hash !== ""){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);
//add hash to the current scroll position
window.location.hash = this.hash;
}
});
#17
1
Tested and Verified Code
测试和验证代码
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
#18
1
I'm surprised no one has posted a native solution that also takes care of updating the browser location hash to match. Here it is:
我很惊讶没有人发布一个本地解决方案来更新浏览器位置散列以匹配。这里是:
let anchorlinks = document.querySelectorAll('a[href^="#"]')
for (let item of anchorlinks) { // relitere
item.addEventListener('click', (e)=> {
let hashval = item.getAttribute('href')
let target = document.querySelector(hashval)
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
})
history.pushState(null, null, hashval)
e.preventDefault()
})
}
See tutorial: http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml
看到教程:http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml
#19
0
I did this for both "/xxxxx#asdf" and "#asdf" href anchors
我这样做是为了“/xxxxx#asdf”和“#asdf”href锚。
$("a[href*=#]").on('click', function(event){
var href = $(this).attr("href");
if ( /(#.*)/.test(href) ){
var hash = href.match(/(#.*)/)[0];
var path = href.match(/([^#]*)/)[0];
if (window.location.pathname == path || path.length == 0){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
window.location.hash = hash;
}
}
});
#20
-7
jQuery is the best!
jQuery是最棒的!
$('a').click(function(){
//code here
});
#1
886
Update April 2018: There's now a native way to do this:
更新2018年4月:现在有一个本地的方法:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
This is currently only supported in the most bleeding edge browsers.
这目前只在最糟糕的边缘浏览器中支持。
For older browser support, you can use this jQuery technique:
对于旧的浏览器支持,您可以使用jQuery技术:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
And here's the fiddle: http://jsfiddle.net/9SDLw/
这是小提琴:http://jsfiddle.net/9SDLw/
If your target element does not have an ID, and you're linking to it by its name
, use this:
如果您的目标元素没有ID,并且您通过它的名称链接到它,请使用以下方法:
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
For increased performance, you should cache that $('html, body')
selector, so that it doesn't run every single time an anchor is clicked:
为了提高性能,您应该缓存$('html, body')选择器,这样它就不会在每次单击锚点时运行:
var $root = $('html, body');
$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
If you want the URL to be updated, do it within the animate
callback:
如果要更新URL,请在动态回调中进行:
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
#2
146
The correct syntax is:
正确的语法是:
//Smooth scrolling with links
$('a[href*=\\#]').on('click', function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
$('html,body').animate({scrollTop:$(location.hash).offset().top}, 500);
});
Simplifying: DRY
简化:干
function smoothScrollingTo(target){
$('html,body').animate({scrollTop:$(target).offset().top}, 500);
}
$('a[href*=\\#]').on('click', function(event){
event.preventDefault();
smoothScrollingTo(this.hash);
});
$(document).ready(function(){
smoothScrollingTo(location.hash);
});
Explanation of href*=\\#
:
解释href * = \ \ #:
-
*
means it matches what contains#
char. Thus only match anchors. For more about the meaning of this, see here - *表示它匹配包含# char的内容。因此只匹配定位。更多关于这个的意义,请看这里
-
\\
is because the#
is a special char in css selector, so we have to escape it. - \是因为#是css选择器中的一个特殊字符,所以我们必须转义它。
#3
20
$('a[href*=#]').click(function(event){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
event.preventDefault();
});
this worked perfect for me
这对我来说是完美的
#4
8
I suggest you to make this generic code :
我建议你制定这个通用代码:
$('a[href^="#"]').click(function(){
var the_id = $(this).attr("href");
$('html, body').animate({
scrollTop:$(the_id).offset().top
}, 'slow');
return false;});
You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide
您可以在这里看到一篇非常好的文章:jquery- effth - scroll-defiled
#5
5
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Official: http://css-tricks.com/snippets/jquery/smooth-scrolling/
官方:http://css-tricks.com/snippets/jquery/smooth-scrolling/
#6
4
Using JQuery:
使用JQuery:
$('a[href*=#]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
#7
2
Adding this:
添加:
function () {
window.location.hash = href;
}
is somehow nullifying the vertical offset
是否取消了垂直偏移量
top - 72
in Firefox and IE, ut not in Chrome. Basically, the page scrolls smoothly to the point at which it should stop based upon the offset, but then jumps down to where the page would go without the offset.
在Firefox和IE中,ut不是在Chrome中。基本上,页面平滑地滚动到基于偏移量应该停止的位置,然后跳转到页面没有偏移量的位置。
It does add the hash to the end of the url, but pressing back does not take you back to the top, it just removes the hash from the url and leaves the viewing window where it sits.
它确实将散列添加到url的末尾,但是按下back并不会将您带回到顶部,它只是从url中删除散列,并将查看窗口留在它所在的位置。
Here is the full js I am using:
这里是我使用的全部js:
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top - 120
}, 500, function () {
window.location.hash = href;
});
return false;
});
#8
2
This solution will also work for the following URLs, without breaking anchor links to different pages.
此解决方案也适用于以下url,而不会中断指向不同页面的锚定链接。
http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor
./index.html
./index.html#anchor
etc.
等。
var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});
I haven't tested this in all browsers, yet.
我还没有在所有浏览器中进行测试。
#9
2
This will make it easy to allow jQuery to discern your target hash and know when and where to stop.
这将使jQuery更容易识别目标散列,并知道何时何地停止。
$('a[href*="#"]').click(function(e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
#10
2
The answer given works but disables outgoing links. Below a version with an added bonus ease out (swing) and respects outgoing links.
给出的答案是有效的,但是禁止输出链接。下面的版本增加了额外的额外好处,可以轻松退出(swing)并尊重传出的链接。
$(document).ready(function () {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
#11
2
HTML
HTML
<a href="#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
or With absolute Full URL
或者使用绝对完整的URL
<a href="https://somewebsite.com/#target" class="smooth-scroll">
Link
</a>
<div id="target"></div>
jQuery
jQuery
$j(function() {
$j('a.smooth-scroll').click(function() {
if (
window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&& window.location.hostname == this.hostname
) {
var target = $j(this.hash);
target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$j('html,body').animate({
scrollTop: target.offset().top - 70
}, 1000);
return false;
}
}
});
});
#12
2
Modern browsers are a little faster these days. A setInterval might work. This function work well in Chrome and Firefox these days.(A little slow in safari, didn't bother with IE)
现在的浏览器快了一点。setInterval可能工作。这个功能目前在Chrome和Firefox中运行良好。(safari有点慢,不用IE)
function smoothScroll(event) {
if (event.target.hash !== '') { //Check if tag is an anchor
event.preventDefault()
const hash = event.target.hash.replace("#", "")
const link = document.getElementsByName(hash)
//Find the where you want to scroll
const position = link[0].getBoundingClientRect().y
let top = 0
let smooth = setInterval(() => {
let leftover = position - top
if (top === position) {
clearInterval(smooth)
}
else if(position > top && leftover < 10) {
top += leftover
window.scrollTo(0, top)
}
else if(position > (top - 10)) {
top += 10
window.scrollTo(0, top)
}
}, 6)//6 milliseconds is the faster chrome runs setInterval
}
}
#13
1
Here is the solution I implemented for multiple links and anchors, for a smooth scroll:
下面是我为多个链接和锚点实现的一个平滑滚动的解决方案:
http://www.adriantomic.se/development/jquery-localscroll-tutorial/ if you have your navigation links set up in a navigation div and declared with this structure:
http://www.adriantomic.se/development/jquer-localscroll-tutorial/如果您的导航链接设置在一个导航div中,并使用以下结构声明:
<a href = "#destinationA">
and your corresponding anchor tag destinations as so:
以及相应的锚标记目的地:
<a id = "destinationA">
Then just load this into the head of the document:
然后将其加载到文档的头部:
<!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>
<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>
<script type = "text/javascript">
$(document).ready(function()
{
// Scroll the whole document
$('#menuBox').localScroll({
target:'#content'
});
});
</script>
Thanks to @Adriantomic
由于@Adriantomic
#14
1
If you have a simple button on the page to scroll down to a div and want the back button to work by jumping to top, just add this code:
如果你在页面上有一个简单的按钮向下滚动到一个div,并且想要后退按钮通过跳转到顶部来工作,只需添加以下代码:
$(window).on('hashchange', function(event) {
if (event.target.location.hash=="") {
window.scrollTo(0,0);
}
});
This could be extended to jump to different divs too, by reading the hash value, and scrolling like Joseph Silbers answer.
这也可以扩展为跳转到不同的div,通过读取散列值,并像Joseph Silbers一样滚动。
#15
1
Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;
不要忘记offset()函数将元素的位置赋给文档。所以当你需要滚动你的元素相对于它的父元素你应该使用它;
$('.a-parent-div').find('a').click(function(event){
event.preventDefault();
$('.scroll-div').animate({
scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
}, 500);
});
The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.
关键是获取scroll-div的scrollTop并将其添加到scrollTop。如果不这样做,position()函数总是会给出不同的位置值。
#16
1
$("a").on("click", function(event){
//check the value of this.hash
if(this.hash !== ""){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);
//add hash to the current scroll position
window.location.hash = this.hash;
}
});
#17
1
Tested and Verified Code
测试和验证代码
<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
#18
1
I'm surprised no one has posted a native solution that also takes care of updating the browser location hash to match. Here it is:
我很惊讶没有人发布一个本地解决方案来更新浏览器位置散列以匹配。这里是:
let anchorlinks = document.querySelectorAll('a[href^="#"]')
for (let item of anchorlinks) { // relitere
item.addEventListener('click', (e)=> {
let hashval = item.getAttribute('href')
let target = document.querySelector(hashval)
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
})
history.pushState(null, null, hashval)
e.preventDefault()
})
}
See tutorial: http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml
看到教程:http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml
#19
0
I did this for both "/xxxxx#asdf" and "#asdf" href anchors
我这样做是为了“/xxxxx#asdf”和“#asdf”href锚。
$("a[href*=#]").on('click', function(event){
var href = $(this).attr("href");
if ( /(#.*)/.test(href) ){
var hash = href.match(/(#.*)/)[0];
var path = href.match(/([^#]*)/)[0];
if (window.location.pathname == path || path.length == 0){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
window.location.hash = hash;
}
}
});
#20
-7
jQuery is the best!
jQuery是最棒的!
$('a').click(function(){
//code here
});