【问题标题】:javascript help; pausing autorefreshjavascript帮助;暂停自动刷新
【发布时间】:2015-02-01 06:08:13
【问题描述】:

想办法让我的聊天 div 区域不会刷新和烦人地滚动到底部。在搜索了我能想出的唯一解决方案之后,将全局设置为某个值并在 onfocus 和 onblur 返回时更改它。

javascript 从来都不是我最擅长的领域,我想它可能只是我自己。

var chatarea = document.getElementById('usertalk');

window.onload=  function() {
    chatarea.scrollTop = chatarea.scrollHeight;
}

var chatfocus = false;


chatarea.onfocus=function(){ chatfocus = true; }

chatarea.onblur=function(){ chatfocus = false; }

setInterval("updateChat()", 5000);

function updateChat(){
    var ajaxRequest;
    ajaxRequest = new XMLHttpRequest();
    ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                if(chatfocus === false){ 
                    chatarea.innerHTML = ajaxRequest.responseText;
                    chatarea.scrollTop = chatarea.scrollHeight; 
                }
            }
    }
        ajaxRequest.open("GET", "comments.php?t=<?php echo $topicc; ?>", true);
        ajaxRequest.send(null);
}

如果 javascript 会打印我的错误,我可能会弄清楚或搜索到足以理解。我尝试了许多不同的变体并将其分配给窗口,但脚本仍然无法工作。我终于放弃并继续使用 php,我现在可以调用一个编辑表单来替换我想要自动刷新的同一个 div 中的评论,并且也需要为此暂停这个脚本。但是再次不知道在不问问题的情况下实现 js。

【问题讨论】:

    标签: javascript ajax scroll refresh


    【解决方案1】:

    “usertalk”在执行时不存在,因此附加事件处理程序失败。将您的事件处理程序放在 onload 函数中:

    var chatarea = null;
    window.onload=  function() {
        chatarea = document.getElementById('usertalk');
        chatarea.scrollTop = chatarea.scrollHeight;
        chatarea.onfocus=function(){ chatfocus = true; }
        chatarea.onblur=function(){ chatfocus = false; }
    }
    

    编辑:没有意识到您还在 updateChat 中引用了 chatarea,在 onload 的范围之外将其定义为 null,但仅在页面加载后使用 getElementById。

    【讨论】:

    • 脚本仍然不想做任何事情,如果设置一个新的 object.getelementbyid('usertalk') 而不是使用 chatarea 对象并在我的 updateActivity 函数中删除我的(如果 chatfocus==false),它的行为就像它通常这样做我相信修复了我的错误的第一部分。
    • 嗯,不太确定。为 onload 和模糊/焦点事件添加一些警报 - 哪些函数实际上正在触发?
    • 起初没有什么想提醒的,然后我注意到我的页面页脚中有一个 window.onload。我想不能超过一个?注释掉页脚脚本并触发 onload 警报,但 onfocus 和 onblur 不会发出警报
    【解决方案2】:

    我显然不能在 div 区域上设置 onfocus 或 onblur 事件?

    在尝试了所有可能的方法来让这些事件工作并更改一个值之后,我不太清楚如何设置为全局而不猜测直到成功,我制作了一个输入按钮来启用/禁用我的自动 updateChat 功能并设置值在我隐藏的 html 表单中。

    我还发现了一些有用的网站,例如 jshint.com 来诊断可能的错误。抱歉不知道

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 2023-01-30
      相关资源
      最近更新 更多