【发布时间】:2017-03-15 23:01:32
【问题描述】:
我有一个应用程序,其中一个 div 表的 contenteditable 属性默认设置为 false。用户可以单击 div,将其 contenteditable 属性更改为 true,然后他们可以添加文本,然后单击“保存”按钮,将属性更改回 false。
当用户在不使用空格或换行符的情况下添加超出设置的 div 最大宽度的文本时会出现问题。例如,
“超过 div 宽度的非常长的名称”
当contenteditable 为true 时,此文本将在最大宽度处开始自动换行,这正是我想要保留的行为。使用我们的示例:
"真的很长的名字 超越 div 的宽度”
当contenteditable 是false 时,当用户单击“保存”按钮时会发生这种情况,此文本的换行符被删除,名称溢出到 div 的边界之外(它将单词放在一个行而不是将其分成几个)。按照我们的示例,文本将从上面变为:
“Areallylongnamethatsurpassesthewidthofthediv”(这会溢出 div 的边界,不是我想要的)
哪些 css 属性导致了非contenteditable div 的这种行为?
当contenteditable 设置为false 时,有没有办法可以保留自动换行符? Overflow: scroll 或 hidden 不是我的应用程序的最佳解决方案。
这是一个说明问题的 sn-p:
$('div').attr("contenteditable", false);
$('div').on('click', function(e) {
$(this).attr("contenteditable", true);
$(this).focus();
$(this).text("");
});
function saveAppt() {
$('div').attr("contenteditable", false);
$('div').prop("readonly", true);
}
div {
height: 100%;
width: 100%;
padding: 10px;
max-width: 120px;
max-height: 120px;
vertical-align: middle;
text-align: center;
display: table-cell;
outline: none;
white-space: pre-wrap;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click the div then start typing something</p>
<div contenteditable="true" class="appt-text">If you start typing normally the line breaks enter on their own and it is awesome! This is what I want after we press "save" even if there are no spaces entered!</div>
<br />
<div contenteditable="true" class="appt-text">WhenYouTypeAReallyLongNameItWillNotHaveLineBreaksAndSurpassTheBorderOfTheDiv</div>
<br />
<button onclick="saveAppt()">save</button>
【问题讨论】:
标签: jquery css line contenteditable line-breaks