由于某种原因,当这篇文章被更新时我从未收到过通知...昨晚,我有了一个关于如何确定换行位置的绝妙想法......我会重建字符串,并每次检查宽度,它起作用了,所以我来这里分享它......结果发现我落后了1周。
无论如何,有两个重要的事情:
您提供的代码使用了我曾经想到的同样绝妙的想法(做得好),但是当我测试它时,它正确地打破了第一行,然后在每个字符后添加了一个换行符(在链接jsfiddle.net上测试)。
我添加了我的代码,它使用jquery并使用span的宽度来确定何时断开。起初我尝试使用div的宽度,但是div.width()返回默认宽度而不是内容的宽度。
我知道这可能不适用于所有浏览器,因此,如果有人知道如何使其完美或接近完美,请慷慨分享。
首先,样式对于在文本区域和div之间同步字体(所有属性),设置大小以及(对于IE)删除自动出现的滚动条是必要的。
.inputArea {
width:200px;
height:100px;
font-family:Arial;
font-size:12px;
overflow: auto;
border: 1px solid #cccccc;
padding:0;
margin:0;
}
.divArea {
font-family:Arial;
font-size:12px;
}
接下来,我包含了jQuery和我的自定义函数:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#breakUp").click(function () {
showLineBreaks();
addLineBreaks();
});
function showLineBreaks() {
content = $("#textEntered").val();
//replace line breaks in content with "|" to allow for replacement below
content = content.replace("\r\n", "<br>");
content = content.replace("\r", "<br>");
content = content.replace("\n", "<br>");
$("#unedited").html(content);
}
function addLineBreaks() {
content = $("#textEntered").val();
//replace line breaks in content with "|" to allow for replacement below
content = content.replace("\r\n", "|");
content = content.replace("\r", "|");
content = content.replace("\n", "|");
tempContent = "";
$("#edited").html("");
for (var i = 0; i ");
} else {
tempContent = $("#edited").html();
$("#edited").html(tempContent + content.charAt(i));
if ($("#edited").width() > 200) {
$("#edited").html(tempContent + "<br>" + content.charAt(i));
}
}
}
}
});
<script>
最后,我的HTML测试页面
Enter text into the textarea below (Set to 200 px width, 100 px height)<br>
<textarea id="textEntered" class="inputArea"></textarea>
<br><br>
The div below will display that text WITHOUT wrapping, BUT replacing all existing line breaks with <br><br>
<div id="unedited"></div>
<br>
The following div will display that text with line breaks ADDED to fit the wrapping<br>
<div class="divArea"><span id="edited"></span></div>
<br>
<button id="breakUp">Click Here to Convert</button>