打开焦点时展开文本区域

expand textarea when onFocus

本文关键字:文本 区域 焦点      更新时间:2023-09-26

我有很多textarea字段,我想让它们在聚焦时都展开

下面是我的代码演示:http://jsfiddle.net/PU73y/

问题是,当我点击它们时,它们不会扩展。为什么呢?

感谢
<textarea id='txt1' class='txt' refID='1' style='height: 15px;'>this is testing of textrea  </textarea>

$(function() {
    $(".txt").focus(function(){
        var element = $(this);
        var refID = element.attr("refID");
    //  alert(refID);
        $('#txt' + refID).focus (function() {
            $('#txt' + refID).animate({
                width: 400,
                height: 200
            }, 1000);
        });
        $('#txt' + refID).blur(function() {
            $('#txt' + refID).animate({
                width: 400,
                height: 20
            }, 1000);
        });
    });
});

http://jsfiddle.net/Y3rMM/

CSS…

.expand {
    height: 1em;
    width: 50%;
    padding: 3px;
}

HTML…

<textarea class="expand" rows="1" cols="10"></textarea>
jQuery…

$('textarea.expand').focus(function () {
    $(this).animate({ height: "4em" }, 500);
});

你可以用CSS来完成,不需要JavaScript:

textarea {
    height: 15px;
}
textarea:focus {
    height: 200px;
    width: 400px; 
}

看到小提琴

http://jsfiddle.net/PU73y/3/

您在初始焦点处理程序中设置了第二个焦点处理程序,因此您需要再次单击以触发该处理程序。我在这里所做的只是删除了内部处理程序:

$(function() {
    $(".txt").focus(function(){
        var element = $(this);
        var refID = element.attr("refID");
    //  alert(refID);

            $('#txt' + refID).animate({
                width: 400,
                height: 200
            }, 1000);

        $('#txt' + refID).blur(function() {
            $('#txt' + refID).animate({
                width: 400,
                height: 20
            }, 1000);
        });
    });
});

可以运行:http://jsfiddle.net/PU73y/4/

您的问题是您在第一个焦点之后仅在$('#txt' + refID)上创建了侦听器