i got a problem. i have a textarea with fixed width and height (750x393px) and large font-size (eg. 100px). if you type in this textarea, the font-size should automatically be reduced so the typed text fits into the textarea. if you delete some chars the font-size should increase.
you know what i mean? there should be no overflow and no scrollbar. the font-size should decrease or increase, so that the text fits into the textarea.
a found a similar script which would be perfect, but this is a div, not a textarea and i dont know how to change this into a textarea:
HTML:
<div class="border" id="border">
<div class="block" id="input" contenteditable="true">Click to edit</div>
</div>
JS:
$('#border').click(function(){
$('#input').focus();
});
$('#input').keyup(function(event){
while ( $(this).height() > 200) {
$(this).css('font-size', '-=1');
}
if (event.keyCode == 8 || event.keyCode == 46) {
while ( $(this).height() <= 200 && $(this).css('font-size') <= "25px") {
$(this).css('font-size', '+=1');
}
$(this).css('font-size', '-=1');
}
});
CSS:
.block {
width:400px;
font-size:25px;
font-family:'Helvetica';
}
.block:focus {
outline: none;
}
.border {
border: 1px solid #000;
width:400px;
height: 200px;
padding: 7px;
cursor:text;
}
look at jsfiddle: http://jsfiddle.net/gwyqsk0s/
and here is a script with a textarea, but the font-size doesnt increase, if i delete some chars: http://jsfiddle.net/XCXJb/1/
can someone help me with that?
This part is a problem:
$(this).css('font-size', '+=1');
It should be:
$(this).css('font-size', (parseInt($(this).css('font-size')) + 1) + 'px');
It is quite tricky. At first, you have to find out the height
of the text in the resizeable textarea
. To do this, we create another textarea
, which has height
set to 0 px, so we can check its text height
easily by scrollHeight
property.
We also have to pass the text from main textarea
to the dummy textarea
on keypress.
HTML :
<textarea id="textarea"></textarea>
<textarea id="dummy"></textarea>
JS:
function getHeight(){
$("#dummy").val( $("#textarea").val() );
return $("#dummy").prop("scrollHeight");
}
$('#textarea').keyup(function(event){
while ( getHeight() > $(this).height()) {
$(this).css('font-size', '-=1');
$("#dummy").css('font-size', '-=1');
}
if (event.keyCode == 8 || event.keyCode == 46) {
while ( getHeight() <= $(this).height() && $(this).css('font-size') <= "25px") {
$(this).css('font-size', '+=1');
$("#dummy").css('font-size', '+=1');
}
$(this).css('font-size', '-=1');
$("#dummy").css('font-size', '-=1');
}
});
CSS:
#textarea, #dummy {
width: 200px;
font-size: 18px;
}
#textarea {
height: 100px;
resize: none;
overflow-y: hidden;
}
#dummy {
visibility: hidden;
height: 0px;
}
A working fiddle is here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.