我如何用JavaScript调用这个函数

How do I invoke this function with JavaScript?

本文关键字:函数 调用 JavaScript 何用      更新时间:2023-09-26

我只是使用基本级别的javascript。今天我发现了下面的内容,当新数据添加到DIV时,向下滚动DIV层。我无法理解如何调用函数。是用window.onload函数吗?或者其他的。我应该在哪里声明DIV名称呢?

代码。

var chatscroll = new Object();
chatscroll.Pane = 
    function(scrollContainerId)
    {
        this.bottomThreshold = 25;
        this.scrollContainerId = scrollContainerId;
    }
chatscroll.Pane.prototype.activeScroll = 
    function()
    {
        var scrollDiv = document.getElementById(this.scrollContainerId);
        var currentHeight = 0;
        if (scrollDiv.scrollHeight > 0)
            currentHeight = scrollDiv.scrollHeight;
        else 
            if (objDiv.offsetHeight > 0)
                currentHeight = scrollDiv.offsetHeight;
        if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
            scrollDiv.scrollTop = currentHeight;
        scrollDiv = null;
    }
更新1:

<script type="text/javascript">
    var chatscroll = new Object();
    var chatScrollPane = new chatscroll.Pane('div1');
    chatScrollPane.activeScroll()
    chatscroll.Pane = function (scrollContainerId) {
    this.bottomThreshold = 25;
    this.scrollContainerId = scrollContainerId;
}
    chatscroll.Pane.prototype.activeScroll = function () {
    var scrollDiv = document.getElementById(this.scrollContainerId);
    var currentHeight = 0;
    if (scrollDiv.scrollHeight > 0)
        currentHeight = scrollDiv.scrollHeight;
    else
        if (objDiv.offsetHeight > 0)
            currentHeight = scrollDiv.offsetHeight;
    if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
        scrollDiv.scrollTop = currentHeight;
    scrollDiv = null;
}
</script>

chatscroll.Pane被设计为构造函数。您可以这样构造一个实例:

new chatscroll.Pane('somescrollContainerId');

如果将返回值赋值给变量,则返回值可以重用。

var chatScrollPane = new chatscroll.Pane('somescrollContainerId');

您传入的scrollContainerId将是您想要使用此对象的HTML文档中DIV元素的ID (id属性)。

你不需要在你的window.onload中声明它,但那肯定不会有什么坏处。构造函数所做的就是创建一个新对象,将this的值设置为新对象,在其中创建和设置bottomThresholdscrollContainerId属性,然后在构造函数完成时返回这个新对象。

只要确保在文档完全解析之后才调用activeScroll函数,因为它实际上进入文档以检索和操作元素。