我有一个应用程序,默认情况下,div表将contenteditable
属性设置为false。用户可以单击div,将其contenteditable
属性更改为true,然后可以添加文本,然后单击“保存”按钮,将属性更改为false。
当用户在不使用空格或换行符的情况下添加超出div的set max-width的文本时,会出现问题。例如,
“Areallylongnamethatsurpassesthewidthofthediv”
当contenteditable
为true
时,此文本将以最大宽度启动自动换行符,这正是我想要保留的行为。使用我们的例子:
“Areallylongname thatsurpassesthe widthofthediv“
当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>
答案 0 :(得分:1)
看起来word-wrap: break-word
就是您所需要的;看看下面。
这是a snapshot默认样式表的{{3}},它将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);
}
&#13;
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;
}
&#13;
<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>
&#13;