jQuery 文本区域调整宽度和高度的大小



我正在尝试为Firefox和Chrome创建jQuery插件,这将使textarea自动增长高度和宽度。这就是我所做的。

.HTML:

<div class="textbox">
    <textarea>Some Text</textarea>
</div>

.CSS:

body, html {
    height: 100%;
    width: 100%;
    padding: 0;
    margin: 0;
}
.textbox {
    position: absolute;
    border: 4px dashed #CCCCCC;
    min-width: 30px;
    padding: 8px;
}

.textbox textarea {
    background: transparent;
    padding: 0;
    margin: 0;
    resize: none;
    font-family: Arial, sans-serif;
    font-size: 60px;
    overflow: hidden;
    width: 100%;
    height: 100%;
    border: none;
    white-space: nowrap;
}
.hiddendiv {
    display: none;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

.JS:

$(function() {
    $.fn.textbox = function(options) {
        options = options || {};
        var maxWidth = options.maxWidth || $(window).width(),
            maxHeight = options.maxHeight || $(window).height();
        this.each(function() {
            var elem = $(this),
                clone = $("<div class='hiddendiv'></div>").appendTo("body"),
                textarea = elem.find("textarea"),
                content = "";
            function setMaxSize() {
                var widthSpace = elem.outerWidth(true) - elem.width();
                var heightSpace = elem.outerHeight(true) - elem.height();
                var newMax = {
                    "max-width": maxWidth - widthSpace,
                    "max-height": maxHeight - heightSpace
                };
                elem.css(newMax);
                clone.css(newMax);
            }
            function adjust() {
                clone.css({
                    "font-family": textarea.css("font-family"),
                    "font-size": textarea.css("font-size")
                });
                content = textarea.val().replace(/n/g, '<br>&nbsp;');
                if (content === "") {
                    content = "&nbsp;";
                }
                clone.html(content);
                elem.css({
                    height: clone.height(),
                    width: clone.width() + 5
                });
            }
            textarea.on("keyup", adjust);
            setMaxSize();
            adjust();
        });
    };
    $(".textbox").textbox();
});

我有几个问题:

  1. 每当我输入一个字母并展开框时,只有在 Firefox 中我才会奇怪地闪烁。我怎样才能摆脱这种眨眼?
  2. 在Chrome中,当我输入一个字母时,第一个字母向后移动,然后返回到其位置。我该如何防止这种情况?
  3. 在Chrome中,每当我输入一个长单词"Sdfsdfsdfwejhrkjsdhfsdf"时,文本在达到最大宽度时不会换行,但会出现一个新行。如何修复此行为?

你可以在.textbox元素上使用CSS过渡,即:transition: all 0.5s;

最新更新