Jquery在Firefox和Chrome中滚动到底部

时间:2012-04-29 20:42:20

标签: javascript jquery firefox google-chrome

function run_battle() {

if(battlenow.length>0) { 
var div = document.getElementById('show_battle');
    $("#show_battle").animate({ scrollTop: $("#show_battle").prop("scrollHeight") -       $('#show_battle').height() }, 100);
var attempt = battlenow.shift(); 
div.innerHTML += attempt;
    $("#show_battle").animate({ scrollTop: $("#show_battle").prop("scrollHeight") - $('#show_battle').height() }, 100);
setTimeout("run_battle()",800);
  }
}

这是我到目前为止所拥有的。它在firefox中运行良好。然而在Chrome中,它根本不起作用。我正在使用Jquery 1.7.1,这就是为什么我使用.prop而不是.attr。

战斗阵列是这样的。

battlenow.push('Alan hit Joe<br><br>');
battlenow.push('Joe fainted<br><br>Battle Over');

如果有帮助的话。

谢谢。

1 个答案:

答案 0 :(得分:0)

这是我使用的代码,可以在所有浏览器中滚动到特定元素。此代码滚动最小量以获取屏幕上的元素,您可能需要不同的东西。请注意对webkit浏览器的检查:

(function($) {

  $.fn.scrollMinimal = function() {

    var cTop = this.offset().top;
    var cHeight = this.outerHeight(true);
    var windowTop = $(window).scrollTop();
    var visibleHeight = $(window).height();

    if (cTop < windowTop) {
      $(jQuery.browser.webkit ? "body": "html")
        .animate({'scrollTop': cTop}, 'slow', 'swing');
    } else if (cTop + cHeight > windowTop + visibleHeight) {
      $(jQuery.browser.webkit ? "body": "html")
        .animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing');
    }
  };

}(jQuery));

叫做:

$('#actions').scrollMinimal();