我有一个textarea(固定大小),它会被一些文本填充,然后调整大小以适应(字体已更改)。
下面的代码在Chrome,Firefox等中运行良好,但不是IE(版本7/8/9,它也必须)。
在非IE中,文本被调整大小并很好地适应textares,但在IE中,textarea的每一行之间存在巨大差距。
我试过设置行高,但它似乎不起作用。我已经读过它与height of the font的结果,这意味着在一个范围内包裹每一行并设置负的上边距。
任何想法都非常感激。
代码示例;
HTML
<span id="inner-text">
<textarea readonly="readonly"
cols="10"
rows="5"
class="messagetext"
style="width:400px; border:none;height:100px;overflow-y:hidden; resize:none;color: #D31245;"
>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</textarea>
</span><span id="temp" style="visibility:hidden"></span>
JS
$(function() {
var while_counter = 1;
var txt = $('textarea.messagetext');
var font_size = txt.css('font-size').replace(/\D/g,'');
var scHeight = txt.get(0).scrollHeight;
var txtHeight = txt.height();
while ( scHeight > (txtHeight+10) ) {
font_size = (font_size - 1);
txtHeight = (txtHeight + 15);
while_counter = while_counter + 1;
}
var lines = txt.val().split('\n');
var total_lines = lines.length;
var span_width = $('#inner-text').width() - 5;
var temp_span = $('#temp');
// now calculate line wraps
$.each(lines, function(){
// temp write to hidden span
temp_span.html(String(this));
// check width
if (temp_span.width() > 400) {
total_lines = total_lines + 1;
}
});
txt.css('font-size', font_size+'px');
txt.height( (total_lines * font_size) + (total_lines * 1.14) + 10);
});
答案 0 :(得分:0)
将以下代码复制到一个html文件中并检入IE
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('hi');
var while_counter = 1;
var txt = $('textarea.messagetext');
var font_size = txt.css('font-size').replace(/\D/g,'');
var scHeight = txt.get(0).scrollHeight;
var txtHeight = $(txt).height();
while ( scHeight > (txtHeight+10) ) {
font_size = (font_size - 1);
txtHeight = (txtHeight + 15);
while_counter = while_counter + 1;
}
var lines = txt.val().split('\n');
var total_lines = lines.length;
var span_width = $('#inner-text').width() - 5;
var temp_span = $('#temp');
// now calculate line wraps
$.each(lines, function(){
// temp write to hidden span
temp_span.html(String(this));
// check width
if (temp_span.width() > 400) {
total_lines = total_lines + 1;
}
});
$(txt).css('font-size', font_size+'px');
$(txt).innerHeight( (total_lines * font_size) + (total_lines * 1.14) + 10);
});
</script>
</head>
<body>
<span id="inner-text">
<textarea readonly="readonly"
cols="10"
rows="5"
class="messagetext"
style="width:400px; border:none;height:100px;overflow:hidden;resize:none;color: #D31245;"
>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</textarea>
</span><span id="temp" style="visibility:hidden"></span>
</body>
</html>