JS实现自适应高度表单文本框的方法


本文实例讲述了JS实现自适应高度表单文本框的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>JS实现自适应高度的表单文本框</title>
    <style type="text/css">
        #shadow, #text { font: 12px/16px Arial; width: 200px; overflow: hidden; height: 16px; }
        #shadow { position: absolute; border-width: 0px; padding: 0px; visibility: hidden; }
        #text { resize: none; }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            var text = document.getElementById("text"); //用户看到的文本框
            var shadow = document.getElementById("shadow"); //隐藏的文本框
            text.oninput = //非IE的
            text.onpropertychange = //IE的
            onchange;
           
            function onchange() {
                shadow.value = text.value;
                setHeight();
                setTimeout(setHeight, 0); //针对IE 6/7/8的延迟, 否则有时会有一个字符的出入
                function setHeight() { text.style.height = shadow.scrollHeight + "px"; }
            }
        };
    </script>
</head>
<body>
    <textarea id="text"></textarea>
    <textarea id="shadow"></textarea>
</body>
</html>

希望本文所述对大家的javascript程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3