Czy mimo to za pomocą CSS lub Javascript ustaw wysokość textarea na podstawie zawartości? Mam kodowany wysokość w moim CSS, ale chciałem, żeby był domyślny, więc nie ma pionowego paska przewijania przy ładowaniu strony?Czy mimo to istnieje wysokość "autofitu" w polu tekstowym w zależności od zawartości przy ładowaniu strony?
Odpowiedz
Jak około http://www.jacklmoore.com/autosize/ Upuść automatyczne przekształcanie w dowolne strona internetowa i powinna po prostu działać. Źródło jest krótkie i dobrze komentowane, jeśli jesteś ciekawy, jak to działa.
// Example:
$(document).ready(function(){
$('textarea').autosize();
});
To nie jest tylko ładowanie strony: jest dynamiczne (chociaż prawdopodobnie możliwe jest uzyskanie efektu za pomocą tej wtyczki). Dynamiczny został zapytany pod adresem: http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize/25566909#25566909 –
Można użyć Automatyczne ustawienie rozmiaru wtyczki używając jQuery UI Autoresize
Oto html,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://css-tricks.com/examples/TextareaTricks/js/autoresize.jquery.min.js"></script>
<textarea></textarea>
i tutaj jest jQuery,
$('textarea').autoResize();
zobaczyć DEMO
Może dodać '$ ('textarea'). change()', aby wywołać zmianę rozmiaru podczas ładowania strony? Pytanie nie chciało mieć pionowego paska przewijania przy ładowaniu strony, co może sugerować, że tekst może być wypełniony wcześniej. – mfirdaus
Hej może iść z ExpandingTextArea wtyczki w którym niewidzialny klon pre element jest utrzymywany za swoim tekstowym. Ilekroć wysokość tego pre zmienia się, obszar tekstowy jest aktualizowany.
To jest proste tylko to "expanding.js" i "jQuery" w swoją stronę i klasę Add "rozszerzającej" do pola tekstowego, do którego u trzeba rozwinąć.
<script src='expanding.js'></script>
<textarea class='expanding'></textarea>
Śledź the link więcej szczegółów i Demo
Uwaga: To będzie działać na obciążenia dokumentu dla już dodanych tekstów
@leora, czy dobrze z powyższym wyjaśnieniem. Może to być wymagane, którego szukasz. :) – Mazzu
Bez wtyczek można zrobić coś takiego
$(document).ready(function(){
elem=document.getElementById('#elemid');
while(elem.clientHeight < elem.scrollHeight) {elem.height(elem.height()+10)}
});
Zmiana rozmiaru textarea podczas gdy ma ha ve pasek przewijania (tak elem.clientHeight < elem.scrollHeight). Możesz to zrobić całkiem łatwo, nawet bez JQuery, w prostym javascript.
Nie przetestowałem kodu, to tylko "koncepcja".
EDIT: Głupi mi, że to o wiele łatwiejsze, bez pętle ...
if (elem.clientHeight < elem.scrollHeight) elem.style.height=elem.scrollHeight+"px";
Nie wiem dlaczego, ale wydaje się, moja wyszukiwarka przyniósł mi inne rozwiązanie (a „how-to” Tutorial):
http://www.sitepoint.com/build-auto-expanding-textarea-3/
EDIT:
oto kod ..
/**
* TextAreaExpander plugin for jQuery
* v1.0
* Expands or contracts a textarea height depending on the
* quatity of content entered by the user in the box.
*
* By Craig Buckler, Optimalworks.net
*
* As featured on SitePoint.com:
* http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/
*
* Please use as you wish at your own risk.
*/
/**
* Usage:
*
* From JavaScript, use:
* $(<node>).TextAreaExpander(<minHeight>, <maxHeight>);
* where:
* <node> is the DOM node selector, e.g. "textarea"
* <minHeight> is the minimum textarea height in pixels (optional)
* <maxHeight> is the maximum textarea height in pixels (optional)
*
* Alternatively, in you HTML:
* Assign a class of "expand" to any <textarea> tag.
* e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea>
*
* Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height.
* e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea>
* The textarea will use an appropriate height between 50 and 200 pixels.
*/
(function($) {
// jQuery plugin definition
$.fn.TextAreaExpander = function(minHeight, maxHeight) {
var hCheck = !($.browser.msie || $.browser.opera);
// resize a textarea
function ResizeTextarea(e) {
// event or initialize element?
e = e.target || e;
// find content length and box width
var vlen = e.value.length, ewidth = e.offsetWidth;
if (vlen != e.valLength || ewidth != e.boxWidth) {
if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));
e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
e.style.height = h + "px";
e.valLength = vlen;
e.boxWidth = ewidth;
}
return true;
};
// initialize
this.each(function() {
// is a textarea?
if (this.nodeName.toLowerCase() != "textarea") return;
// set height restrictions
var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);
// initial resize
ResizeTextarea(this);
// zero vertical padding and add events
if (!this.Initialized) {
this.Initialized = true;
$(this).css("padding-top", 0).css("padding-bottom", 0);
$(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
}
});
return this;
};
})(jQuery);
// initialize all expanding textareas
jQuery(document).ready(function() {
jQuery("textarea[class*=expand]").TextAreaExpander();
});
Wyszedłem komentarze w kodzie, ponieważ nie jest moja praca;)
Testowany w chromie
Czysta rozwiązanie javascript (bez wtyczki, No jQuery)
w akcji: fiddle
Stworzyłem 3 funkcje ns:
- wysokość linii get
- liczba get linii
- ustawić wysokość pola tekstowego podczas wpisywania (zdarzenie wejściowe)
//attach input event
document.getElementById('ta').addEventListener('input', autoHeight, false);
function autoHeight(e){
var lh = getLineHeightInPixels(e.target);
var nol = getNumberOfLines(e.target);
var ht = lh * nol;
e.target.style.height = ht + 'px';
}
function getNumberOfLines(el){
var text = el.value
var lines = text.split(/\r|\r\n|\n/);
return lines.length;
}
function getLineHeightInPixels(el){
var tempDiv = document.createElement('div');
tempDiv.style.visibility = 'hidden';
tempDiv.style.fontFamily = getComputedStyle(el).getPropertyValue('font-family');
tempDiv.style.fontSize = getComputedStyle(el).getPropertyValue('font-size');
tempDiv.style.lineHeight = getComputedStyle(el).getPropertyValue('line-height');
tempDiv.style.fontVariant = getComputedStyle(el).getPropertyValue('font-variant');
tempDiv.style.fontStyle = getComputedStyle(el).getPropertyValue('font-style');
tempDiv.innerText = 'abcdefghijklmnopqrstuwxyz';
document.documentElement.appendChild(tempDiv);
var ht = parseInt(getComputedStyle(tempDiv).getPropertyValue('height'))
document.documentElement.removeChild(tempDiv);
return (ht);
}
//set height on document load
document.addEventListener('DOMContentLoaded', function(){document.getElementById('ta').style.height = getLineHeightInPixels(document.getElementById('ta')) + 'px';}, false);
<textarea id="ta"></textarea>
Jeśli nie przeszkadza Ci w tym wskaniak Obszar tekstu można użyć
$(document).ready(function(){
tx = $('#textarea')
tx.height(tx.prop('scrollHeight'));
})
i tutaj jest Fiddle
inny Fiddle ten posiada min i max-width zestawu.
ale wtyczek jak auto-size
Wysokość wzrostu pola tekstu wejściowego.
lub można spróbować to plug-in
Jedynym css używam poniżej na textarea
jest jego width
, nie ma potrzeby, aby ustawić początkowy height
. overflow
nie powinna być konieczna albo jako scrollHeight
, które należy stosować, jest:
pomiar wysokości zawartości danego elementu, w tym zawartości niewidocznych na ekranie w wyniku przekroczenia.
scrollHeight: MDN
Jeśli chcesz pracować z Internet Explorer, chociaż, to jest niezbędne do korzystania z overflow: auto
jak inaczej IE nalega na dodanie pionowy pasek przewijania (choć nie ma nic do przewijania).
Należy pamiętać, że width
również nie musi być określona, ale jest to właściwość najczęściej określona w odniesieniu do tego tematu.
To jest JavaScript potrzebne:
document.addEventListener("DOMContentLoaded", function(event) {
var ta = document.getElementById('ta');
ta.style.height = ta.scrollHeight + 'px';
});
Gdy DOM został załadowany height
pola tekstowego jest ustawiony na jego scrollHeight
.
Powyżej znajduje się pełna strona do testowania:
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
<style>
textarea {
width: 300px;
overflow: auto;
}
</style>
</head>
<body>
<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var ta = document.getElementById('ta');
ta.style.height = ta.scrollHeight + 'px';
});
</script>
</body>
</html>
razie potrzeby, kod może być stosowane do wszystkich pola tekstowe na stronie:
document.addEventListener("DOMContentLoaded", function(event) {
var tas = document.getElementsByTagName('textarea');
for (var i=0; i < tas.length; i++) {
tas[i].style.height = tas[i].scrollHeight + 'px';
}
});
HTML
<div id="container">
<textarea >
1
12
123
1234
12345
123456
1234567
</textarea>
</div>
CSS
div#container textarea {
overflow-y: hidden; /* prevents scroll bar flash */
padding-top: 1.1em; /* prevents text jump on Enter keypress */
}
JQuery
// auto adjust the height of
$('#container').on('keyup', 'textarea', function (e){
$(this).css('height', 'auto');
$(this).height(this.scrollHeight);
});
$('#container').find('textarea').keyup();
Tutaj jest czystym rozwiązaniem JavaScript. Bez jquery, bez wtyczek itp. DEMO
Jak to działa? Załóżmy, że masz domyślny rozmiar czcionki/wysokość linii/etc. Cóż, twoje pole tekstowe ma około 11 znaków na szerokość 100 pikseli. Jeśli możemy o tym pamiętać, możemy skorzystać z tej funkcji.
function textareaSetSize(elem, width)
{
var length = elem.value.length;
//about 11 characters per 100 pixels
var estimatedLines = Math.round(length/(width/100*11));
//alert('Estimated number of lines: ' + length);
elem.style.width = width + 'px';
elem.rows = estimatedLines;
}
Następnie ..
var selector = document.getElementsByClassName('textarea');
for(var i = 0; i < selector.length; i++)
{
selector[i].onkeyup = function(){
textareaSetSize(this, 400);
};
}
html ...
<button id="reset">Empty</button>
<textarea class="textarea" id="autosize"></textarea>
<textarea class="textarea" id="autosize2"></textarea>
<textarea class="textarea" id="autosize3"></textarea>
<textarea class="textarea" id="autosize4"></textarea>
runnning go ...
textareaSetSize(ta, 500);
textareaSetSize(ta2, 400);
textareaSetSize(ta3, 400);
textareaSetSize(ta4, 400);
Nie jest to idealne rozwiązanie, jeśli tak widzisz innowację, daj mi znać.
sprawdź moją odpowiedź tutaj - http://stackoverflow.com/a/17286049/2303467 – shubhra
czy rozważałeś użycie contenteditable? –
możliwy duplikat: http://stackoverflow.com/questions/12323383/how-to-resize-textarea-according-to-content, http://stackoverflow.com/questions/17772260/textarea-auto-height –