我怎样才能模仿GChat的可滚动区域?

时间:2011-08-19 14:06:56

标签: javascript jquery html

GChat会在新文本出现时将textarea滚动到最后,但是如果用户滚动离开末尾,它会等待您向下滚动以继续此行为。

只使用HTML,Javascript和JQuery,怎么能模仿这种行为?

2 个答案:

答案 0 :(得分:3)

每次添加数据时,请执行以下操作:

this.scrollTop = this.scrollHeight;

这只是强制您滚动到底部的标准Javascript。要强迫某人在已经位于底部时保持滚动到底部,请执行以下操作:

var elem = document.getElementById('myElementName');
var atBottom = (elem.scrollTop >= (elem.scrollHeight - elem.clientHeight));
// add your text updates here
if(atBottom) elem.scrollTop = elem.scrollHeight;

http://jsfiddle.net/xjmha/4/

的示例

(忽略小提琴的其他版本......我用jQuery失败了。)

答案 1 :(得分:1)

尝试这样的事情:)

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style type="text/css">
textarea {
    height: 80px;
    width: 450px;
}
</style>
<script type="text/javascript">
var foo = function(){
    var t = document.getElementById('foo');
    if(t['data-scrollinglocked'])return;
    var h = t.scrollHeight;
    t.scrollTop = h;
}

var moo = function(){
    var t = document.getElementById('foo');
t.innerHTML = t.innerHTML + new Date()+"\n";
}

var init = function(){
    // global scope ;)
    mooInterval = setInterval("moo()",1000);
    fooInterval = setInterval("foo()",500);

    var t = document.getElementById('foo');
    t['data-scrollinglocked'] = 0;
    t.onmouseout = function(){
        t['data-scrollinglocked'] = 0;
    };
    t.onmouseover = function(){
        t['data-scrollinglocked'] = 1;
    };
    t.onclick = function(){
        t['data-scrollinglocked'] = 1;
    };
    t.onblur = function(){
        t['data-scrollinglocked'] = 1;
    };
    t.onfocus = function(){
        t['data-scrollinglocked'] = 1;
    };
    t.onblur= function(){
        t['data-scrollinglocked'] = 0;
    };
}
</script>
</head>
<body>
<div class="foo"></div>
<textarea id="foo"></textarea>
<script>init();</script>
</body>

</html>