如何使用 jQuery 向上或向下滚动页面到一个锚点?

我正在寻找一种方法,包括一个幻灯片效果,当你点击一个链接到一个本地锚或向上或向下的页面。

我想让你有一个这样的链接:

link text, img etc.

也许添加了一个类,这样你就知道你想要这个链接是一个滑动链接:

link text, img etc.

然后,如果点击这个链接,页面就会向上或向下滑动到所需的位置(可以是div、标题、页面顶部等)。


这是我之前写的:

    $(document).ready(function(){
$(".scroll").click(function(event){
//prevent the default action for the click event
event.preventDefault();


//get the full url - like mysitecom/index.htm#home
var full_url = this.href;


//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
var parts = full_url.split("#");
var trgt = parts[1];


//get the top offset of the target anchor
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;


//goto that anchor by setting the body scroll top to anchor top
$('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
});
});
495657 次浏览

描述

你可以使用jQuery.offset()jQuery.animate()来做到这一点。

检查jsFiddle示范

样本

function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}


scrollToAnchor('id3');

更多的信息

我坚持我的原始代码,还包括一个淡出在“回顶”链接,利用这段代码和一点从这里:

http://webdesignerwall.com/tutorials/animated-scroll-to-top

效果很好:)

$(function() {
$('a#top').click(function() {
$('html,body').animate({'scrollTop' : 0},1000);
});
});

在这里测试:

http://jsbin.com/ucati4

你可能想要添加offsetTopscrollTop值,以防你动画的不是整个页面,而是一些嵌套的内容。

例句:

var itemTop= $('.letter[name="'+id+'"]').offset().top;
var offsetTop = $someWrapper.offset().top;
var scrollTop = $someWrapper.scrollTop();
var y = scrollTop + letterTop - offsetTop


this.manage_list_wrap.animate({
scrollTop: y
}, 1000);
function scroll_to_anchor(anchor_id){
var tag = $("#"+anchor_id);
$('html,body').animate({scrollTop: tag.offset().top},'slow');
}

这让我的生活轻松多了。你基本上放入元素id标签和它的滚动,而不需要很多代码

< a href = " http://balupton.github。io / jquery-scrollto noreferrer“rel = > http://balupton.github.io/jquery-scrollto/ < / >

在Javascript中

$('#scrollto1').ScrollTo();

在你的html中

<div id="scroollto1">

我在这一页的最下面

下面的解决方案对我来说很有效:

$("a[href^=#]").click(function(e)
{
e.preventDefault();
var aid = $(this).attr('href');
console.log(aid);
aid = aid.replace("#", "");
var aTag = $("a[name='"+ aid +"']");
if(aTag == null || aTag.offset() == null)
aTag = $("a[id='"+ aid +"']");


$('html,body').animate({scrollTop: aTag.offset().top}, 1000);
}
);

SS慢滚动

这个解决方案不需要锚标记,但你当然需要匹配菜单按钮(任意属性,例如'ss')与你的html中的目标元素id。

ss="about"带你到id="about"

$('.menu-item').click(function() {
var keyword = $(this).attr('ss');
var scrollTo = $('#' + keyword);
$('html, body').animate({
scrollTop: scrollTo.offset().top
}, 'slow');
});
.menu-wrapper {
display: flex;
margin-bottom: 500px;
}
.menu-item {
display: flex;
justify-content: center;
flex: 1;
font-size: 20px;
line-height: 30px;
color: hsla(0, 0%, 80%, 1);
background-color: hsla(0, 0%, 20%, 1);
cursor: pointer;
}
.menu-item:hover {
background-color: hsla(0, 40%, 40%, 1);
}


.content-block-header {
display: flex;
justify-content: center;
font-size: 20px;
line-height: 30px;
color: hsla(0, 0%, 90%, 1);
background-color: hsla(0, 50%, 50%, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="menu-wrapper">
<div class="menu-item" ss="about">About Us</div>
<div class="menu-item" ss="services">Services</div>
<div class="menu-item" ss="contact">Contact</div>
</div>


<div class="content-block-header" id="about">About Us</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.


That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="services">Services</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.


That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>
<div class="content-block-header" id="contact">Contact</div>
<div class="content-block">
Lorem ipsum dolor sit we gonna chung, crazy adipiscing phat. Nullizzle sapizzle velizzle, shut the shizzle up volutpizzle, suscipizzle quizzle, away vizzle, arcu. Pellentesque my shizz sure. Sed erizzle. I'm in the shizzle izzle funky fresh dapibus turpis tempus shizzlin dizzle. Maurizzle my shizz nibh izzle turpizzle. Gangsta izzle fo shizzle mah nizzle fo rizzle, mah home g-dizzle. I'm in the shizzle eleifend rhoncizzle fo shizzle my nizzle. In rizzle habitasse crazy dictumst. Yo dapibus. Curabitizzle tellizzle urna, pretizzle break it down, mattis izzle, eleifend rizzle, nunc. My shizz suscipit. Integer check it out funky fresh sizzle pizzle.


That's the shizzle et dizzle quis nisi sheezy mollis. Suspendisse bizzle. Morbi odio. Vivamizzle boofron. Crizzle orci. Cras mauris its fo rizzle, interdizzle a, we gonna chung amizzle, break it down izzle, pizzle. Pellentesque rizzle. Vestibulum its fo rizzle mi, volutpat uhuh ... yih!, ass funky fresh, adipiscing semper, fo shizzle. Crizzle izzle ipsum. We gonna chung mammasay mammasa mamma oo sa stuff brizzle yo. Cras ass justo nizzle purizzle sodales break it down. Check it out venenatizzle justo yo shut the shizzle up. Nunc crackalackin. Suspendisse bow wow wow placerizzle sure. Fizzle eu ante. Nunc that's the shizzle, leo eu gangster hendrerizzle, gangsta felis elementum pizzle, sizzle aliquizzle crunk bizzle luctus pede. Nam a nisl. Fo shizzle da bomb taciti gangster stuff i'm in the shizzle i'm in the shizzle per conubia you son of a bizzle, per inceptos its fo rizzle. Check it out break it down, neque izzle cool nonummy, tellivizzle orci viverra leo, bizzle semper risizzle arcu fo shizzle mah nizzle.
</div>

小提琴

https://jsfiddle.net/Hastig/stcstmph/4/

你还应该考虑目标对象有一个填充,因此使用position而不是offset。你也可以考虑一个潜在的导航条,你不想重叠的目标。

const $navbar = $('.navbar');


$('a[href^="#"]').on('click', function(e) {
e.preventDefault();


const scrollTop =
$($(this).attr('href')).position().top -
$navbar.outerHeight();


$('html, body').animate({ scrollTop });
})

假设你的href属性链接到一个带有相同名称标记iddiv(像往常一样),你可以使用下面的代码:

超文本标记语言

<a href="#goto" class="sliding-link">Link to div</a>


<div id="goto">I'm the div</div>

JAVASCRIPT - Jquery

$(".sliding-link").click(function(e) {
e.preventDefault();
var aid = $(this).attr("href");
$('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});

我使用jQuery的方法只是让所有嵌入的锚链接滑动,而不是立即跳转

它与桑蒂Nunez的答案非常相似,但它更可靠的

支持

  • Multi-framework环境。
  • 在页面完成加载之前。
<a href="#myid">Go to</a>
<div id="myid"></div>
// Slow scroll with anchors
(function($){
$(document).on('click', 'a[href^=#]', function(e){
e.preventDefault();
var id = $(this).attr('href');
$('html,body').animate({scrollTop: $(id).offset().top}, 500);
});
})(jQuery);

以下是对我有效的解决方案。这是一个通用函数,适用于所有引用名为aa标记

$("a[href^=#]").on('click', function(event) {
event.preventDefault();
var name = $(this).attr('href');
var target = $('a[name="' + name.substring(1) + '"]');
$('html,body').animate({ scrollTop: $(target).offset().top }, 'slow');
});

注意1:确保在html中使用双引号"。如果使用单引号,则将上述代码部分更改为var target = $("a[name='" + name.substring(1) + "']");

注2:在某些情况下,特别是当你从引导中使用粘贴条时,命名的a将隐藏在导航条下面。在这些情况下(或任何类似的情况),您可以减少滚动的像素数量以实现最佳位置。例如:$('html,body').animate({ scrollTop: $(target).offset().top - 15 }, 'slow');将带你到顶部剩下15个像素的target

我在https://css-tricks.com/snippets/jquery/smooth-scrolling/上偶然发现了这个例子,它解释了每一行代码。我觉得这是最好的选择。

https://css-tricks.com/snippets/jquery/smooth-scrolling/

你可以选择本地:

window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});


window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});


document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});

或者用jquery:

$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {


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) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
}
});

好的,最简单的方法是:-

在点击函数(Jquery): -

$('html,body').animate({scrollTop: $("#resultsdiv").offset().top},'slow');

超文本标记语言

<div id="resultsdiv">Where I want to scroll to</div>