51

一部のページ内でjQueryのページスクロールを使用しようとしていたところ、スムーズなページスクロールを正常に行うことができました。私が今持っている唯一の問題は、別のページからそれをしようとしたときです。つまり、ページ内のリンクをクリックすると、新しいページが読み込まれ、特定の div 要素までスクロールする必要があります。

ページ内をスクロールするために使用したコードは次のとおりです。

var jump=function(e)
{
       //prevent the "normal" behaviour which would be a "hard" jump
       e.preventDefault();
   //Get the target
   var target = $(this).attr("href");
   //perform animated scrolling
   $('html,body').animate(
   {
           //get top-position of target-element and set it as scroll target
           scrollTop: $(target).offset().top
   //scrolldelay: 2 seconds
   },2000,function()
   {
           //attach the hash (#jumptarget) to the pageurl
           location.hash = target;
   });

}

$(document).ready(function()
{
       $('a[href*=#]').bind("click", jump);
       return false;
});

アイデアが明確であることを願っています。

ありがとう

非常に重要な注:上記のコードは同じページ内でうまく機能しますが、私が求めているのは、あるページからリンクをクリックして別のページに移動し、ターゲットまでスクロールすることです. それが今はっきりしていることを願っています。ありがとう

4

7 に答える 7

66

基本的にこれを行う必要があります:

  • 他のページへのリンクにターゲット ハッシュを含めます ( href="other_page.html#section")
  • ハンドラーでready、通常はハッシュによって決定されるハードジャンプスクロールをクリアし、できるだけ早くページを一番上にスクロールして呼び出しますjump()-これを非同期で行う必要があります
  • イベントが指定されjump()ていない場合はlocation.hash、ターゲットを作成します
  • また、この手法ではジャンプが間に合わない可能性があるため、html,bodyすぐに非表示にして、スクロールしてゼロに戻したら表示することをお勧めします。

これは、上記を追加したコードです。

var jump=function(e)
{
   if (e){
       e.preventDefault();
       var target = $(this).attr("href");
   }else{
       var target = location.hash;
   }

   $('html,body').animate(
   {
       scrollTop: $(target).offset().top
   },2000,function()
   {
       location.hash = target;
   });

}

$('html, body').hide();

$(document).ready(function()
{
    $('a[href^=#]').bind("click", jump);

    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump();
        }, 0);
    }else{
        $('html, body').show();
    }
});

Chrome/Safari、Firefox、Opera で動作確認済み。IEは知らないけど。

于 2012-03-21T13:36:31.460 に答える
25

リンクにハッシュを入れます:

<a href="otherpage.html#elementID">Jump</a>

そして他のページでは、次のことができます:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

他のページでは、elementIDスクロールするように id が設定された要素が必要です。もちろん、その名前を変更できます。

于 2012-03-11T06:35:19.950 に答える
11

PetrとSarfrazの回答を組み合わせると、次のようになります。

page1.html:

<a href="page2.html#elementID">Jump</a>

page2.html:

<script type="text/javascript">
    $(document).ready(function() {
        $('html, body').hide();

        if (window.location.hash) {
            setTimeout(function() {
                $('html, body').scrollTop(0).show();
                $('html, body').animate({
                    scrollTop: $(window.location.hash).offset().top
                    }, 1000)
            }, 0);
        }
        else {
            $('html, body').show();
        }
    });
</script>
于 2012-10-26T04:33:53.747 に答える
6

scrollTo プラグインの使用をお勧めします

http://demos.flesler.com/jquery/scrollTo/

jquery cssセレクターでscrolltoを設定できます。

$('html,body').scrollTo( $(target), 800 );

私はこのプラグインとその方法の正確さで幸運に恵まれました。過去にクロスブラウザを使用し.offset()たり失敗したりして、同じ効果を達成する他の方法がありました. .position()そのようなメソッドを使用できないと言っているわけではありませんが、クロスブラウザで実行する方法があると確信しています.scrollToの方が信頼性が高いことがわかりました.

于 2012-03-21T18:35:37.217 に答える
2

これを行うことができる再利用可能なプラグインを作成しました... イベントへのバインディングをプラグイン自体の外に残しました。

jQuery(function ($) {

    /**
     * This small plugin will scrollTo a target, smoothly
     *
     * First argument = time to scroll to the target
     * Second argument = set the hash in the current url yes or no
     */
    $.fn.smoothScroll = function(t, setHash) {
        // Set time to t variable to if undefined 500 for 500ms transition
        t = t || 500;
        setHash = (typeof setHash == 'undefined') ? true : setHash;

        // Return this as a proper jQuery plugin should
        return this.each(function() {
            $('html, body').animate({
                scrollTop: $(this).offset().top
            }, t);

            // Lets set the hash to the current ID since if an event was prevented this doesn't get done
            if (this.id && setHash) {
                window.location.hash = this.id;
            }
        });
    };

});

次に、これをオンロードして、ハッシュをチェックし、そこにある場合は、jQuery のセレクターとして直接使用してみます。当時はこれを簡単にテストできませんでしたが、少し前に本番サイト用に同様のものを作成しました。これがすぐに機能しない場合はお知らせください。解決策を調べます。

(スクリプトは onload セクション内にある必要があります)

if (window.location.hash) {
    window.scrollTo(0,0);
    $(window.location.hash).smoothScroll();
}

次に、href 属性にハッシュのみを含むアンカーの onclick にプラグインをバインドします。

(スクリプトは onload セクション内にある必要があります)

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

    $($(this).attr('href')).smoothScroll();
});

jQuery は、一致自体が失敗した場合は何もしないので、ページ上のターゲットが見つからない場合の適切なフォールバックがあります \o/

アップデート

ハッシュしかない場合に上部にスクロールする代替の onclick ハンドラー:

$('a[href^="#"]').click(function(e) {
    e.preventDefault();
    var href = $(this).attr('href');

    // In this case we have only a hash, so maybe we want to scroll to the top of the page?
    if(href.length === 1) { href = 'body' }

    $(href).smoothScroll();
});

これは、ページ内のスクロールを示す単純なjsfiddleでもあります.onloadはセットアップが少し難しいです...

http://jsfiddle.net/sg3s/bZnWN/

更新 2

そのため、ウィンドウが既に要素のオンロードまでスクロールしているという問題が発生する可能性があります。これwindow.scrollTo(0,0);は、ページを左上にスクロールするだけです。上記のコード スニペットに追加しました。

于 2012-03-21T22:42:27.387 に答える