元素的scrollheight给出未定义的值

元素的scrollheight给出未定义的值

本文介绍了元素的scrollheight给出未定义的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an element I've given CSS overflow: scroll;. Now in jQuery I want to have it's original height (containing all child elements' height). Children under this element are dynamically changing. I want to have height on scroll event.Here is the code:

$("#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()));
}

问题:它抛出 scrollHeight未定义错误。出了什么问题?

Issue: It throws scrollHeight is undefined error. What's wrong?

推荐答案

jQuery中没有 scrollHeight - 它是 scrollTop()

There is no scrollHeight in jQuery - it's scrollTop():

var elemHeight = $("#container").scrollTop();
var scrollHeight = $("#scrollbars").scrollTop();

或者,如果你想使用原生的 scrollHeight property,你需要直接访问jQuery对象中的DOM元素,如下所示:

Alternatively if you want to use the native scrollHeight property, you need to access the DOM element in the jQuery object directly, like this:

var elemHeight = $("#container")[0].scrollHeight;
var scrollHeight = $("#scrollbars")[0].scrollHeight;

这篇关于元素的scrollheight给出未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:26