web-dev-qa-db-ja.com

jQuery scrollTop()はSafariまたはChrome(Windows)で動作しないようです。

「ヘルプ」スタイルのウィンドウをロードして、ページ上の特定のポイントにスクロールできるようにする簡単なセットアップがあります。多かれ少なかれ、コードは次のようになります。

var target = /* code */;
target.offsetParent().scrollTop(target.offset().top - fudgeValue);

スクロールのターゲットとファッジの値は、ページにドロップされたいくつかのヒントによって決まります。このメカニズムのどこでも問題はありません。 FirefoxとIE8では、上記のコードは私が望むように機能します。スクロールボックス(この場合はページ本体)は、指示されたときにウィンドウ内の適切なポイントに含まれているものを正しくスクロールします。

ChromeおよびSafariでは、scrollTop()の呼び出しは明らかに何もしません。すべての数字はOKで、ターゲットは正しいものを参照します(そしてoffsetParent()は実際にbody要素)、しかし、何も起こりません。グーグルで見ればわかるように、これは動作するはずです。

それが重要な場合、これはjQuery 1.3.2です。

テストページ: http://gutfullofbeer.net/scrolltop.html

39
Pointy

ええ、bodyを変更してoffsetParentにしようとすると、Chromeにバグがあるようです。 、別のdivを追加して#content divをラップし、that scrollにすることをお勧めします。

html, body { height: 100%; padding: 0; } 
html { width: 100%; background-color: #222; overflow: hidden; margin: 0; } 
body 
{ 
   width: 40em; margin: 0px auto; /* narrow center column layout */
   background-color: white; 
   position: relative; /* allow positioning children relative to this element */
} 
#scrollContainer /* wraps #content, scrolls */
{ 
  overflow: auto; /* scroll! */
  position:absolute; /* make offsetParent */
  top: 0; height: 100%; width: 100%; /* fill parent */
} 
#header 
{ 
  position: absolute; 
  top: 0px; height: 50px; width: 38.5em; 
  background-color: white; 
  z-index: 1; /* sit above #content in final layout */
} 
#content { padding: 5px 14px 50px 5px;  } 

FF 3.5.5でテスト、Chrome 3.0.195.33、IE8

ライブデモ:

$(function() {
        $('#header').find('button').click(function(ev) {
          var button = $(this), target = $('div.' + button.attr('class'));
          var scroll = target.offsetParent().scrollTop(); 
          target.offsetParent().scrollTop(target.offset().top + scroll - 50);
        });
      });
html, body { height: 100%; padding: 0; }
      html { width: 100%; background-color: #222; overflow: hidden; margin: 0; }
      body { width: 40em; margin: 0px auto; background-color: white; position: relative; }
      #scrollContainer { overflow: auto; position:absolute; top: 0; height: 100%; width: 100%; }
      #header { position: absolute; top: 0px; height: 50px; width: 38.5em; background-color: white; z-index: 1; }
      #content { padding: 5px 14px 50px 5px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div id='header'> 
      Header Box
      <button class='A'>A</button> 
      <button class='B'>B</button> 
      <button class='C'>C</button> 
    </div> 
    <div id='scrollContainer'>
    <div id='content'> 
      <div style='height: 50px'> </div> 
      <div class='A'> 
        <h1>A</h1> 
        <p>My name is Boffer Bings. I was born of honest parents in one of the humbler walks of life, my father being a manufacturer of dog-oil and my mother having a small studio in the shadow of the village church, where she disposed of unwelcome babes. In my boyhood I was trained to habits of industry; I not only assisted my father in procuring dogs for his vats, but was frequently employed by my mother to carry away the debris of her work in the studio. In performance of this duty I sometimes had need of all my natural intelligence for all the law officers of the vicinity were opposed to my mother's business. They were not elected on an opposition ticket, and the matter had never been made a political issue; it just happened so. My father's business of making dog-oil was, naturally, less unpopular, though the owners of missing dogs sometimes regarded him with suspicion, which was reflected, to some extent, upon me. My father had, as silent partners, all the physicians of the town, who seldom wrote a prescription which did not contain what they were pleased to designate as _Ol. can._ It is really the most valuable medicine ever discovered. But most persons are unwilling to make personal sacrifices for the afflicted, and it was evident that many of the fattest dogs in town had been forbidden to play with me--a fact which pained my young sensibilities, and at one time came near driving me to become a pirate.
      </div> 
      <div class='B'> 
        <h1>B</h1> 
        <p> 
        Looking back upon those days, I cannot but regret, at times, that by indirectly bringing my beloved parents to their death I was the author of misfortunes profoundly affecting my future.
        <p> 
        One evening while passing my father's oil factory with the body of a foundling from my mother's studio I saw a constable who seemed to be closely watching my movements. Young as I was, I had learned that a constable's acts, of whatever apparent character, are prompted by the most reprehensible motives, and I avoided him by dodging into the oilery by a side door which happened to stand ajar. I locked it at once and was alone with my dead. My father had retired for the night. The only light in the place came from the furnace, which glowed a deep, rich crimson under one of the vats, casting ruddy reflections on the walls. Within the cauldron the oil still rolled in indolent ebullition, occasionally pushing to the surface a piece of dog. Seating myself to wait for the constable to go away, I held the naked body of the foundling in my lap and tenderly stroked its short, silken hair. Ah, how beautiful it was! Even at that early age I was passionately fond of children, and as I looked upon this cherub I could almost find it in my heart to wish that the small, red wound upon its breast--the work of my dear mother--had not been mortal.
      </div> 
      <div class='C'> 
        <h1>C</h1> 
        <p>It had been my custom to throw the babes into the river which nature had thoughtfully provided for the purpose, but that night I did not dare to leave the oilery for fear of the constable. "After all," I said to myself, "it cannot greatly matter if I put it into this cauldron. My father will never know the bones from those of a puppy, and the few deaths which may result from administering another kind of oil for the incomparable _ol. can._ are not important in a population which increases so rapidly." In short, I took the first step in crime and brought myself untold sorrow by casting the babe into the cauldron.
      </div> 
      <div style='height: 75em;'> </div> 
    </div> 
    </div>
23
Shog9

SafariとChrome(Mac)でこの問題が発生し、.scrollTop$("body")で機能するが、$("html, body")、FF、およびIEでは機能しないことを発見しました_ただし、逆の方法でも機能します。単純なブラウザー検出により問題が修正されます。

if($.browser.safari)
    bodyelem = $("body")
else
    bodyelem = $("html,body")

bodyelem.scrollTop(100)

ChromeのjQueryブラウザーの値はSafariなので、検出する必要があるだけです。

これが誰かを助けることを願っています。

46
Carl
 $("body,html,document").scrollTop($("#map_canvas").position().top);

これは、Chrome 7、IE6、IE7、IE8、IE9、FF 3.6、およびSafari 5で機能します。

2012 UPDATE
これはまだ有効ですが、もう一度使用する必要がありました。ときどきpositionが機能しないため、これは代替手段です。

$("body,html,document").scrollTop($("#map_canvas").offset().top);
17
GorillaApe

ブラウザのサポート状況は次のとおりです。

IE8、Firefox、Opera:$("html")

Chrome、Safari:$("body")

だからこれは動作します:

bodyelem = $.browser.safari ? $("body") : $("html") ;
bodyelem.animate( {scrollTop: 0}, 500 );
9
pengkai

スクロールの場合: 'html'またはsetterの 'body'(ブラウザに依存)... 'window 'getter...

テスト用のjsFiddleはこちらです: http://jsfiddle.net/molokoloco/uCrLa/

var $window = $(window), // Set in cache, intensive use !
    $document = $(document),
    $body = $('body'),
    scrollElement = 'html, body',
    $scrollElement = $();

var isAnimated = false;

// Find scrollElement
// Inspired by http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
$(scrollElement).each(function(i) {
    // 'html, body' for setter... window for getter... 
    var initScrollTop = parseInt($(this).scrollTop(), 10);
    $(this).scrollTop(initScrollTop + 1);
    if ($window.scrollTop() == initScrollTop + 1) {
        scrollElement = this.nodeName.toLowerCase(); // html OR body
        return false; // Break
    }
});
$scrollElement = $(scrollElement);

// UTILITIES...
var getHash = function() {
        return window.location.hash || '';
    },
    setHash = function(hash) {
        if (hash && getHash() != hash) window.location.hash = hash;
    },
    getWinWidth = function() {
        return $window.width();
    },
    // iphone ? ((window.innerWidth && window.innerWidth > 0) ? window.innerWidth : $window.width());
    getWinHeight = function() {
        return $window.height();
    },
    // iphone ? ((window.innerHeight && window.innerHeight > 0) ? window.innerHeight : $window.height());
    getPageWidth = function() {
        return $document.width();
    },
    getPageHeight = function() {
        return $document.height();
    },
    getScrollTop = function() {
        return parseInt($scrollElement.scrollTop() || $window.scrollTop(), 10);
    },
    setScrollTop = function(y) {
        $scrollElement.stop(true, false).scrollTop(y);
    },
    myScrollTo = function(y, newAnchror) { // Call page scrolling to a value (like native window.scrollBy(x, y)) // Can be flooded
        isAnimated = true; // kill waypoint AUTO hash
        var duration = 360 + (Math.abs(y - getScrollTop()) * 0.42); // Duration depend on distance...
        if (duration > 2222) duration = 0; // Instant go !! ^^
        $scrollElement.stop(true, false).animate({
            scrollTop: y
        }, {
            duration: duration,
            complete: function() { // Listenner of scroll finish...
                if (newAnchror) setHash(newAnchror); // If new anchor
                isAnimated = false;
            }
        });
    },
    goToScreen = function(dir) { // Scroll viewport page by paginette // 1, -1 or factor
        var winH = parseInt((getWinHeight() * 0.75) * dir); // 75% de la hauteur visible comme unite
        myScrollTo(getScrollTop() + winH);
    };


myScrollTo((getPageHeight() / 2), 'iamAMiddleAnchor');
7
molokoloco

Chrome(チェックした時点ではSafariではありません)にバグがあり、バックグラウンドでタブを開くときにJavascriptのさまざまな幅と高さの測定値に予期しない結果が生じます( バグの詳細はこちら )-6月にバグを記録しましたが、それ以降は未解決のままです。

あなたがしようとしていることでバグに遭遇した可能性があります。

2
Ross Duggan

Safari、Firefox、およびIE7で動作します(IE8を試したことはありません)。簡単なテスト:

<button onclick='$("body,html").scrollTop(0);'>  Top </button>

<button onclick='$("body,html").scrollTop(100);'> Middle </button>

<button onclick='$("body,html").scrollTop(250);'> Bottom </button>

ほとんどの例では、どちらか一方または両方を使用しますが、逆順です(つまり、「html、body」)。

乾杯。

(セマンティックな純粋主義者は、私のチョップをつぶさないでください-私はこれを数週間探していました、これはXHTML厳格を検証するシンプルの例です。 OCDの安心のための抽象化とイベントバインドの肥大化。jQueryフォーラム、SO、およびGのメンバーは商品をせき立てることができませんでした。

2
PapaK
setTimeout(function() { 
   $("body,html,document").scrollTop( $('body').height() ); 
}, 100);

これはおそらく時間が10ミリ秒であっても動作するはずです。

2
Dima

どの要素が別の要素のoffsetParentであるかは明確に指定されておらず、ブラウザによって異なる場合があります。探しているスクロール可能な親であるとは限りません。

本体自体もページのメインのスクロール可能な要素であってはなりません。一般的には回避したいQuirksモードのみです。

offsetTop/offsetLeft/offsetParentの測定値は、それだけではそれほど役に立ちません。ループで使用して、合計ページ相対座標(jQueryのposition()と同様)。スクロールする要素がどれであるかを知り、それと子孫targetの間のページ座標の違いを調べて、スクロールする量を見つけてください。

または、常にスクロールについて話しているページ自体である場合は、location.href= '#'+target.id代わりにナビゲーション。

1
bobince

うまくいきました。jQueryに任せてください。

$("html,body").animate({ scrollTop: 0 }, 1);

基本的には、ブラウザを理解し、ブラウザの違いを考慮してコードを記述する必要があります。 jQueryはクロスブラウザなので、最初のステップを処理する必要があります。そして最後に、スクロールを1ミリ秒でアニメーション化することにより、ブラウザーのjs-engineを偽造します。

1
ozanmuyes

どう?

var top = $('html').scrollTop() || $('body').scrollTop();
1
Andrew Bullock

これはFFとWebKitで機能しているようです。 IEこれまでテストされていません。

$(document).scrollTop();
1

これが事実かどうかはわかりません:

JQueryにGoogleのCDNを使用していました。

置く"https:"//ajax.google.......動作し、Safariがローカルパスとして認識したようです(チェック-要素の検査)

申し訳ありませんが、Safari 7.0.3でのみテスト済みです:(

0
pk10

これは実際にはバグではなく、ブラウザベンダーによる移植の違いにすぎません。

原則として、ブラウザのスニッフィングは避けてください。気の利いたjQuery修正があり、それは答えで示唆されています。

これは私のために働くものです:$('html:not(:animated),body:not(:animated)').scrollTop()

0
Egor Kloos

私はこの問題に直面していたので、このリンクを一番下に作成し、jQuery scrollTopコードを実装しました。Firefox、IEで完全に機能しました。Operaしかし、ChromeとSafari。jQueryを学習しているので、このソリューションが技術的に完璧かどうかはわかりませんが、これでうまくいくことを確認しました。Firefoxで動作する$( 'html')を使用する2つのScrollTopコードを実装しました、など。2番目のものは$( 'html body')を使用します。これはChromeおよびSafariで機能します。

$('a#top').click(function() {

    $('html').animate({scrollTop: 0}, 'slow');
    return false;

    $('html body').animate({scrollTop: 0}, 'slow');
    return false;
});
0
Raj

実際、Safariで機能させるにはアニメーションが必要なようです。私は結局:

if($.browser.safari) 
    bodyelem = $("body");
else 
    bodyelem = $("html,body");

bodyelem.animate({scrollTop:0},{queue:false, duration:100, easing:"linear", complete:callbackFunc});
0
dijipiji

いくつかの質問/回答からソリューションを要約するには:

現在のスクロールオフセットを取得する場合使用:

$(document).scrollTop()

スクロールオフセットを設定するには使用:

$('html,body').scrollTop(x)

スクロールの使用をアニメーション化するには使用:

$('html,body').animate({scrollTop: x});
0
Paul LeBeau

私の場合、ボタンは8つのリンクのうち2つで機能していました。私の解決策は

$("body,html,document").animate({scrollTop:$("#myLocation").offset().top},2500);

これにより、素敵なスクロール効果も作成されました

0
Daniel Lefebvre

WebページをスクロールするときにscrollTop値で自動的に割り当てられる要素の大きな選択肢はありません。

そこで、この小さな関数を作成して、可能性のある要素を反復処理し、求めている要素を返します。

var grab=function (){
    var el=$();
        $('body#my_body, html, document').each(function(){
            if ($(this).scrollTop()>0) {
                el= ($(this));
                return false;
            }
        })
    return el;
}
//alert(grab().scrollTop());

Googleではchromeで本文が取得され、IE-HTML。

(注:htmlまたはbodyにoverflow:autoを明示的に設定する必要はありません。)

0
Anonymous