我有一个应用程序,其中一个 div 表的 contenteditable
属性默认设置为 false。用户可以单击 div,将其 contenteditable
属性更改为 true,然后他们可以添加文本,然后单击“保存”按钮将属性更改回 false。
当用户在不使用空格或换行符的情况下添加超出设置的 div 最大宽度的文本时,会出现问题。例如,
“Areallylongnamethatsurpassesthewidthofthediv”
当 contenteditable
为 true
时,此文本将在最大宽度处开始自动换行,这正是我想要保留的行为。使用我们的示例:
“好长的名字 那超越了 宽度"
当 contenteditable
为 false
时,即用户单击“保存”按钮时发生的情况,此文本的换行符被删除,名称溢出到边界外div 的(它将单词放在一行而不是将其分成几行)。按照我们的示例,文本将从上面更改为:
“Areallylongnamethatsurpassesthewidthofthediv”(这会溢出 div 的边界,不是我想要的)
哪些 css 属性导致非 contenteditable
div 的这种行为?
当 contenteditable
设置为 false 时,有没有办法保留自动换行符? Overflow: scroll
或 hidden
不是我的应用程序的最佳解决方案。
这是一个说明问题的片段:
$('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>
最佳答案
看起来 word-wrap: break-word
是您所需要的;在下面查看。
这是 a snapshot将 break-word
应用于可编辑内容的默认样式表。
$('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;
/* additional style */
word-wrap: break-word;
}
<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 - 当 contenteditable 从 true 设置为 false 时,哪些 css 属性会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42822321/