使用animate.scrolltop和(target).offset()计算固定标头.top;

Mar*_*tin 13 jquery target offset scrolltop jquery-animate

这应该是一个非常基本的问题,但是我早上大部分时间都在扔它,而且此时我已经接近了.我甚至没有一点js foo - 但我找到了一个很好的评论代码块,我希望用它来动画锚链接:

$(document).ready(function() {
$('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump

var target = $(this).attr("href"); //Get the target

var scrollToPosition = $(target).offset().top;

// perform animated scrolling by getting top-position of target-element and set it     as scroll target
$('html, body').stop().animate({ scrollTop: scrollToPosition}, 600, function() {
     location.hash = target;  //attach the hash (#jumptarget) to the pageurl
});

return false;

 });
});
Run Code Online (Sandbox Code Playgroud)

我试图让它落在偏移量()上方30px.顶部 - 我试过了

$('html, body').stop().animate({ scrollTop: scrollToPosition -30}, 600,

这几乎是有效的 - 它去了正确的地方,然后反弹回来.

我也试过了

scrollTop: $(target).offset().top - 20 },

我也试过了

scrollTop: $(hash).offset().top + $('#access').outerHeight()

这似乎没有任何改变.

似乎答案可能就在这里:带有固定标题的JQuery页面滚动问题, 但我似乎无法得到它.

我知道这与其他问题相似 - 但我已经找到了我能找到的东西,而且我已经足够文盲,以至于我无法复制/粘贴任何可以解决问题的东西.

我非常感谢解决方案.

非常感谢,

马丁

PS

我找到的另一块代码确实有用,但是它正在剥离标签,这使得它几乎没用.

$(function(){
$('a[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) {
            var targetOffset = $target.offset().top;
            $('html,body').animate({scrollTop: targetOffset - 30}, 1000);
            return false;
        }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

Ste*_*e O 16

编辑: 你只需要检测固定标题的高度,然后从scrollToPosition你正确的标题中减去它.问题是将window.location.hash = "" + target;页面跳转到具有该ID的元素的顶部.因此,如果你像那样在那里制作动画然后更改为那个哈希,它会像你描述的那样"反弹".这是我们解决这个问题的第一种方式:

// Get the height of the header
var headerHeight = $("div#header").height();

// Attach the click event
$('a[href*=#]').bind("click", function(e) {
    e.preventDefault();

    var target = $(this).attr("href"); //Get the target
    var scrollToPosition = $(target).offset().top - headerHeight;

    $('html').animate({ 'scrollTop': scrollToPosition }, 600, function(){
        window.location.hash = "" + target;
        // This hash change will jump the page to the top of the div with the same id
        // so we need to force the page to back to the end of the animation
        $('html').animate({ 'scrollTop': scrollToPosition }, 0);
    });

    $('body').append("called");
});
Run Code Online (Sandbox Code Playgroud)

这是第一种方法的 jsfiddle:http://jsfiddle.net/yjcRv/1/

进一步编辑: 控制哈希更改事件的更好方法是使用像jQuery Address这样的插件.有了这个,你可以更多地利用你的hashchange事件.这是一个示例用法:

// Get the height of the header
var headerHeight = $("div#header").height();

$.address.change(function(evt){
    var target = "#" + evt["pathNames"][0]; //Get the target from the event data

    // If there's been some content requested go to it…else go to the top
    if(evt["pathNames"][0]){
        var scrollToPosition = $(target).offset().top - headerHeight;
        $('html').animate({ 'scrollTop': scrollToPosition }, 600);
    }else{
        $('html').animate({ 'scrollTop': '0' }, 600);
    }

    return false;
});

// Attach the click event
$('a').bind("click", function(e) {
    // Change the location
    $.address.value($(this).attr("href"));

    return false;
});
Run Code Online (Sandbox Code Playgroud)

这里的实例:http://www.vdotgood.com/stack/user3444.html

注意:您现在不需要将哈希添加到链接href属性.这是一个可以使用jQuery选择器定位的链接:

<!-- This is correct -->
<a href="/target" class="myclass">Target</a>

<!-- These are incorrect -->
<a href="/#/target" class="myclass">Target</a>

<a href="#/target" class="myclass">Target</a>
Run Code Online (Sandbox Code Playgroud)

要定位此链接,您可以使用以下选择器:

$("a.myclass").click(function(){
    $.address.value($(this).attr("href"));
    return false;
});
Run Code Online (Sandbox Code Playgroud)

jQuery Address实际上确实查找具有以下属性的链接:

<a href="/target" rel="address:/target">Target</a>
Run Code Online (Sandbox Code Playgroud)

rel此处的属性包含address:后跟本例中定义的相对URL /target.如果使用此方法,jQuery Address将检测链接并自动触发哈希更改事件.

  • 要让它在Chrome/Safari和其他webkit浏览器中运行,您需要将$('html').animate更改为$('html,body'). (2认同)

Gre*_*egT 7

我知道这是一个老问题(某种程度),但我遇到了类似的问题,网站上有固定的下拉导航.请注意,这是一个流畅的滚动代码片段,但您可以通过更改动画速度轻松实现自动化.

jQuery的:

$('body').on('click','a[href^="#"]',function(event){
    event.preventDefault();
    var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
    //change this number to create the additional off set        
    var customoffset = 75
    $('html, body').animate({scrollTop:target_offset - customoffset}, 500);
});
Run Code Online (Sandbox Code Playgroud)

我已经使用了这段代码很长一段时间没有任何问题.我唯一不喜欢的是,它会抓住任何#tag.所以在像Flexslider插件这样的插件中,导航使用#,我手动将它们从插件中剥离出来.