元素的scrollheight给出未定义的值

Par*_*jar 11 javascript jquery

在我给CSS的元素中overflow: scroll;.现在在jQuery中我希望它具有原始高度(包含所有子元素的高度).这个元素下的孩子是动态变化的.我想在滚动事件上有高度.这是代码:

$("#container").scroll(function(e) {
    scrollAll();
});

function scrollAll(){
    var elemHeight = $("#container").scrollHeight;
    var scrollHeight = $("#scrollbars").scrollHeight;
    var ratio = elemHeight / scrollHeight;

    $("#outup").html( elemHeight +" and "+ scrollHeight +" ratio "+ ratio +" = "+ ($("#container").scrollTop()));
}
Run Code Online (Sandbox Code Playgroud)

问题:它抛出scrollHeight is undefined错误.怎么了?

Ror*_*san 38

scrollHeight在jQuery中没有- 它是scrollTop():

var elemHeight = $("#container").scrollTop();
var scrollHeight = $("#scrollbars").scrollTop();
Run Code Online (Sandbox Code Playgroud)

或者,如果要使用本机scrollHeight属性,则需要直接访问jQuery对象中的DOM元素,如下所示:

var elemHeight = $("#container")[0].scrollHeight;
var scrollHeight = $("#scrollbars")[0].scrollHeight;
Run Code Online (Sandbox Code Playgroud)

  • `$("#container")`返回包装在jQuery对象中的元素,`$("#container")[0]`返回DOM元素本身. (6认同)

Ank*_*kit 12

如果您使用的是Jquery 1.6或更高版本,请使用prop访问该值.

$("#container").prop('scrollHeight')
Run Code Online (Sandbox Code Playgroud)

以前的版本用于从attr获取值,但不是在1.6之后.