0
我正在嘗試爲Firefox和Chrome創建jQuery插件,這將使textarea
自動增長爲高度和寬度。 This is what I have done。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> ');
if (content === "") {
content = " ";
}
clone.html(content);
elem.css({
height: clone.height(),
width: clone.width() + 5
});
}
textarea.on("keyup", adjust);
setMaxSize();
adjust();
});
};
$(".textbox").textbox();
});
我有幾個問題:
- 每當我將ty一封信,並擴大框,只在Firefox中,我得到奇怪的閃爍。我怎樣才能擺脫那種眨眼?
- 在Chrome中,當我鍵入一個字母時,第一個字母向後移動,然後返回到它的位置。我怎樣才能防止這一點?
- 在Chrome中,無論何時輸入一個長詞,例如「Sdfsdfsdfwejhrkjsdhfsdf」,當達到最大寬度時文本都不會破壞新行,但出現一條新行。我該如何解決這個問題?
我不認爲這會解決這個問題,你可以用我的jsfiddle,讓我看看怎麼樣? – Naor
FF中閃爍的問題是由於將文本的某些部分跳轉到另一行並在調整大小後返回而導致的。我會建議你先調整箱子大小。 – Eru