jQuery的scrollTop()似乎并不适用于Safari或Chrome(Windows)

我有一个简单的设置,允许“帮助”样式的窗口被加载和滚动到页面上的特定点。 或多或less的代码如下所示:

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

scroll和fudge值的目标是由页面上的一些提示决定的,而且我对这个机制的任何部分都没有任何问题。 在Firefox和IE8中,上面的代码完全像我想要的那样工作:滚动的框(在这种情况下,页面主体)正确地将所包含的东西滚动到窗口中的正确位置。

然而,在Chrome和Safari中,scrollTop()的调用显然没有任何作用。 所有的数字都没问题,目标指的是正确的东西(而且offsetParent()的确是body元素),但什么都不会发生。 据我可以从谷歌search来看,这应该是工作。 Safari和Chrome下的渲染器有什么好玩的吗?

这是jQuery 1.3.2,如果重要的话。

testing页面: http : //gutfullofbeer.net/scrolltop.html

是的,Chrome在修改body时似乎存在一个错误,试图将其设置为offsetParent 。 作为一个解决方法,我build议你只需添加另一个div来包装#content div,并进行滚动:

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

testing在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> 

我在Safari和Chrome(Mac)中遇到了这个问题,发现.scrollTop可以在$("body")上工作,但不能在$("html, body")工作。 一个简单的浏览器检测修复了这个问题:

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

Chrome的jQuery浏览器值是Safari,所以你只需要做一个检测。

希望这有助于某人。

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

这适用于Chrome 7,IE6,IE7,IE8,IE9,FF 3.6和Safari 5。

2012年更新
这仍然不错,但我不得不再次使用它。 有时position不起作用,所以这是一个替代scheme:

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

浏览器的支持状态是这样的:

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

Chrome,Safari: $("body")

所以这个工作:

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

对于滚动: “HTML”或“身体”二传手 (取决于浏览器)… “窗口”获得者

一个jsFiddletesting在这里: 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'); 

在Chrome浏览器中有一个错误(在我们检查的时候没有在Safari中),当在后台打开标签的时候,Javascript的各种宽度和高度测量结果都会给出意想不到的结果( 这里是bug详细信息 ) – 我们在6月份logging了这个错误, 。

您可能遇到了您正在尝试执行的错误。

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

即使时间是10ms,这也许应该工作。

适用于Safari,Firefox和IE7(还没有试过IE8)。 简单testing:

 <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”)。

干杯。

(而且那里的语义纯粹主义者,不要打破我的排骨 – 我已经找了几个星期,这是一个简单的例子,严格validationXHTML。随意创build27层的抽象和事件绑定膨胀OCD让人放心,请给予应有的信任,因为jQuery论坛上的人们,SO和G都无法咳出货,和平了。

哪个元素是另一个的offsetParent没有被很好地指定,并且可能在不同的浏览器中有所不同。 不能保证是你正在寻找的可滚动的父母。

身体本身也不应该是页面的主要滚动元素。 它只是在怪癖模式,这一般你想避免。

offsetTop / offsetLeft / offsetParent测量本身并不是非常有用,当你在一个循环中使用它们来获得总的页面相关坐标时(如jQuery中的position() )。 你应该知道哪一个是你想要滚动的元素,并找出它与后代target之间的页面坐标的差异,以找出滚动它的多less。

或者,如果它始终是您正在讨论的滚动页面,只需使用location.href= '#'+target.id导航即可。

这似乎是在FF和WebKit工作; IE目前尚未testing。

 $(document).scrollTop(); 

怎么样

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

它为我工作,只是把它留给jQuery。

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

基本上,你应该知道浏览器,并考虑浏览器差异编写代码。 由于jQuery是跨浏览器,它应该处理第一步。 最后你通过在1毫秒内滚动animation来伪造浏览器的js引擎。

当我们滚动一个网页时,没有很多元素可以使用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()); 

在谷歌C​​hrome浏览器将使我们身体,在IE – HTML。

(注意,我们不需要在我们的html或body上明确地设置overflow:auto 。)

我遇到了这个问题,我在底部创build了这个链接,并实现了jQuery的scrollTop代码,它在Firefox,IE,Opera中完美工作,但在Chrome和Safari中无法使用。 我正在学习jQuery,所以我不知道这个解决scheme在技术上是否完美,但是这对我来说是有效的。 我刚刚实现了2个ScrollTop代码,第一个使用$('html'),它适用于Firefox等等。第二个使用$('html body')这适用于Chrome和Safari。

 $('a#top').click(function() { $('html').animate({scrollTop: 0}, 'slow'); return false; $('html body').animate({scrollTop: 0}, 'slow'); return false; }); 

事实上,似乎需要animation才能在Safari中运行。 我结束了:

 if($.browser.safari) bodyelem = $("body"); else bodyelem = $("html,body"); bodyelem.animate({scrollTop:0},{queue:false, duration:100, easing:"linear", complete:callbackFunc}); 

我不确定是否是这样的情况:

我正在使用Google的CDN为jQuery ie

"https:"放在//ajax.google.......之前,似乎Safari将它识别为本地path(通过检查元素进行检查)

对不起,只在Safari 7.0.3中testing:(

我的情况是,button正在为8个链接中的两个工作。 我的解决scheme是

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

这也创造了一个很好的滚动效果

总结几个问题/答案的解决scheme:

如果你想获得当前的滚动偏移量使用:

 $(document).scrollTop() 

要设置滚动偏移量使用:

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

使用animation滚动使用:

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

这不是一个真正的错误,只是浏览器厂商植入的差异。

通常避免浏览器嗅探。 有一个漂亮的jQuery修复,在答案暗示。

这是什么对我有用: $('html:not(:animated),body:not(:animated)').scrollTop()