文本框自动调整大小点击

时间:2012-04-01 17:46:53

标签: jquery

我试图在点击时调整文本框大小。

头脑中的

<style>
.expand {
    height: 1em;
    width: 50%;
    padding: 3px;
}
</style>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
$('textarea.expand').focus(function () {
    $(this).animate({ height: "1000px" }, 500);
});
</script>

和身体:

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

它不会为我扩展。

2 个答案:

答案 0 :(得分:3)

它不起作用的原因是你没有在$(document).ready()上指定事件绑定,因此事件在DOM中存在元素之前被绑定。试试这个:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
$(document).ready(function(){
    $('textarea.expand').focus(function () {
        $(this).animate({ height: "1000px" }, 500);
    });
});
</script>

JS Fiddle demo

值得注意的是,在更新的浏览器中,您不一定需要JavaScript:

.expand {
    height: 1em;
    width: 50%;
    padding: 3px;
    -webkit-transition: all 1s linear;
    -0-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}

.expand:focus {
    height: 1000px;
    -webkit-transition: all 1s linear;
    -0-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -moz-transition: all 1s linear;
    transition: all 1s linear;
}​

JS Fiddle demo

答案 1 :(得分:0)

代码看起来很好,并且它在JS Fiddle中正常运行 - http://jsfiddle.net/Pt3d8/1/。您可能需要检查以确保Google JSAPI正确地提取jQuery!

相关问题