简体   繁体   English

滚动页面到锚点

[英]Scroll Page to Anchor

I have some anchors on a site I'm playing with and I'd like them to scroll to anchors instead of doing a sudden jump to the anchor. 我正在玩的站点上有一些锚点,我希望它们滚动到锚点,而不是突然跳到锚点。 I've tried several posted solutions here on stack overflow but haven't been able to get them to work. 我已经尝试过在堆栈溢出时在这里发布几个解决方案,但是还无法使它们正常工作。 Am I doing something wrong? 难道我做错了什么?

I've tried this code and several like it but they don't seam to work: 我已经试过了这段代码,有些人喜欢它,但是它们却无法正常工作:

$('a').click(function(){
$('html, body').animate({
    scrollTop: $( $(this).attr('href') ).offset().top
}, 500);
return false;
});

The site can be found here and currently only the 'about us' item is anchored: http://jsfiddle.net/pnKu2/ 该站点位于此处,当前仅锚定“关于我们”项目: http//jsfiddle.net/pnKu2/

First instead of selecting all anchors, you should select just your navigation IE: 首先,不要选择所有锚,而应只选择导航IE:

$('.menu-hover-underline').click(function(){
    return false;
});

Next extend this functionality to include the scroll 接下来扩展此功能以包括滚动

$('.menu-hover-underline').click(function(){
    var divId = $(this).text().toLowerCase();
    $('html, body').animate({
        scrollTop: $("#"+divId).offset().top
    }, 500);
    return false;
});

See jsfiddle http://jsfiddle.net/pnKu2/2/ 参见jsfiddle http://jsfiddle.net/pnKu2/2/

Please note I updated your div Ids since all but the about div were id="title". 请注意,由于about div以外的所有id均为id =“ title”,因此我更新了您的div ID。

you could try like this: 您可以这样尝试:

$('a').click(function(e){
     var href = $(this).attr("href");
     var offsetTop = href === "#" ? 0 : $(href).offset().top;

     $('html, body').stop().animate(
     { 
       scrollTop: offsetTop
     }, 1000);

     e.preventDefault();
});

DEMO 演示

Try this 尝试这个

$(function() {
    $('a').click(function(e){
        var top = $( $(this).attr('href') ).offset().top;
        $('html, body').animate({
            scrollTop: top
        }, 500);
        return false;
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM