問題描述
在內容可編輯元素中使用換行符(之後)設置內聯元素的樣式 ‑ 插入符號位置 (Styling an inline element with linebreak (after) within a content editable element ‑ caret position)
我在 contenteditable 元素中設置內聯元素的樣式,以直觀地表示換行符。
First text(Linebreak)
[C]Second Line
我希望能夠將光標放在我無法做到的 [C]
位置。我相信對當前的行為有一個合理的解釋。有人願意解釋一下,也許可以給我提供一種不同的方法嗎?
編輯:顯然它適用於 IE 和 Firefox,但不適用於 Chrome。
.lb{
display:inline;
}
.lb:after{
content: "\21B2\A";
white‑space: pre;
word‑wrap: break‑word;
}
.edit‑box{
border: 1px solid black;
padding: 10px;
}
<div id="test" contenteditable="true" class="edit‑box">
How to style the span element<span class="lb"></span>so it's possible to place the cursor at the beginning of this line, before "S".
</div>
參考解法
方法 1:
You could wrap each new line in a <p>
.
.edit‑box {
border: 1px solid black;
padding: 10px;
}
.edit‑box p {
margin: 0
}
p:not(:last‑child):after {
content: "\21B2";
}
<div id="test" contenteditable="true" class="edit‑box">
<p>How to style the span element</p>
<p>so it's possible to place the cursor at the beginning of this line, before "S".</p>
</div>
Or wrap that 2nd line in a span that displays as a block:
.edit‑box {
border: 1px solid black;
padding: 10px;
}
.edit‑box span {
display: block;
}
<div id="test" contenteditable="true" class="edit‑box">
How to style the span element
<span>so it's possible to place the cursor at the beginning of this line, before "S".</span>
</div>
方法 2:
Try the follow css changes in your lb classes with addition of .lb:before:
.lb{
display:inline;
white‑space: nowrap;
}
.lb:before{
content:'';
display:block;
}
.lb:after{
content: "\21B2\A";
}
This will achieve what you want. What we are doing is that we are telling the main lb to not wrap the text in and around it. Next we create lb before as block to get it into new line and then a lb after to add the cursor and the rest of the text flows along with it. Hope this helps.
方法 3:
I've come up with a different approach by wrapping the BR element with a span as such:
.edit‑box{
border: 1px solid black;
padding: 10px;
}
.icon{
width:15px;
}
.icon::before{
content: "\21B2";
}
<div id="test" contenteditable="true" class="edit‑box">
How to style the span element so it's possible to place the cursor<span class="icon"><br></span> at the beginning of this line, before "at".
</div>
Basically, the linebreak sort of receives a visual dimension and keeps its regular behavior.
For the specific contenteditable element, I capture all keypress events for the return key and paste <span class="icon"><br></span>
, preventing the default behavior.
(by pelican_george、ksav、Nasir T、pelican_george)