0

当用户按 Enter 键时,我一直在尝试更改 textarea 的高度,这样他们就不必滚动了。我可以在 IE 和 Chrome 上管理它,但我无法让它在 Firefox 上运行。请看一下我的代码。我对此真的很陌生。似乎它无法识别事件,我想不出办法。这是我的代码:

<form id="blog-comment-form" method="post" action="index.php">
<textarea id="comment" name="b_com" onkeyup="showmsg()"  placeholder="ADD YOUR COMMENT HERE"></textarea>
<input type="submit" name="submit" value="POST COMMENT"/>
</form>

我正在从外部文件调用该函数。还有我的javascript代码:

function showmsg() {

    if(!event){
           event= window.event;}
    if (event.keyCode==13) {
        var a = document.getElementById("comment");
    var b = document.getElementById("comment").style.scrollHeight;
    a.style.height = ((a.scrollHeight)+6) + "px"; 
}else {
    var a = document.getElementById("comment");
    var b = document.getElementById("testthis").style.height;
    a.style.height = ((a.scrollHeight)+6) + "px"; 
}

}

谢谢你

4

4 回答 4

0

您需要将 rows 属性添加到文本区域。这将帮助您增加 textarea 的高度

于 2013-07-17T21:40:26.980 回答
0

除了使用 onkeyup 属性,你可以用不同的方式监听 keyup 事件,这也会为你创建事件对象:

document.getElementById('comment').addEventListener('keyup', showmsg);

一个工作示例:http: //jsfiddle.net/rotev/FKDVD/1/

在 Firefox 和 Chrome 上测试。

于 2013-07-17T21:54:10.847 回答
0

您的代码有一些问题。在某些浏览器上,您的事件处理可能无法正常工作。

因此,首先,您需要从回调本身获取事件,而不是使用名为 event 的全局变量。

要调整文本区域的大小,您可以使用属性 cols 和 rows。

要处理事件,您可以通过以下方式附加回调:

function init(){
    var e = document.getElementById("comment");
    e.onkeyup = showmsg;
}

有关事件侦听器的更多信息,请查看内容。要调整文本区域的大小,您可以使用行:

function showmsg(event) {
    if (event.keyCode==13) {
        var a = document.getElementById("comment");
        a.rows++;
    }
}

要调用 init,您可以将其与元素主体相关联:

<body onload="init()">

最终代码如下所示:

<html>
<head>
<script>
function init(){
    var e = document.getElementById("comment");
    e.onkeyup = showmsg;
}
function showmsg(event) {
    if (event.keyCode==13) {
        var a = document.getElementById("comment");
        a.rows++;
    }
}
</script>
</head>
<body onload="init()">
<form id="blog-comment-form" method="post" action="index.php">
<textarea id="comment" name="b_com" placeholder="ADD YOUR COMMENT HERE"></textarea>
<input type="submit" name="submit" value="POST COMMENT"/>
</form>
</body>
</html>
于 2013-07-17T21:55:59.697 回答
0

写这个:

function showmsg(event) {

代替:

function showmsg() {

写这个(在 HTML 标记中):

onkeyup="showmsg(event)"

代替:

onkeyup="showmsg()"
于 2013-07-17T22:00:28.447 回答