簡體   English   中英

jQuery textarea調整寬度和高度的大小

[英]jquery textarea resize both width and height

我正在嘗試為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM