14

これはかなり基本的な質問になるはずですが、私は朝のほとんどをそれに投げかけました、そしてこの時点で私はタオルを投げるところです。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;

 });
});

私はそれをoffset()。topの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;
        }
    }
  });
});
4

4 に答える 4

19

EDITED: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");
});

この最初のメソッドの新しい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;
});

ここのライブ例: 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>

このリンクをターゲットにするには、次のようなセレクターを使用します。

$("a.myclass").click(function(){
    $.address.value($(this).attr("href"));
    return false;
});

実際、jQuery Address は次の属性を持つリンクを探します。

<a href="/target" rel="address:/target">Target</a>

ここのrel属性にはaddress:、この場合はユーザーが定義した相対 URL が続きます/target。これを使用すると、jQuery Address がリンクを検出し、ハッシュ変更イベントを自動的に発生させます。

于 2012-01-30T18:52:26.967 に答える
7

これは古い質問(一種)ですが、Webサイトの固定ドロップダウンナビゲーションで同様の問題が発生しました。これはスムーズなスクロールコードスニペットであることに注意してください。ただし、アニメーションの速度を変更することで簡単に自動化できます。

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);
});

私はこのコードのチャンクを長い間問題なく使用してきました。私がそれについて嫌いなのは、#タグを取得することだけです。したがって、ナビゲーションが#を使用するFlexsliderプラグインのようなプラグインでは、プラグインから手動でそれらを削除します。

于 2013-01-02T22:08:18.420 に答える