我有一个 article
,其中一个句子的列表( ol
(,每行。用户可以点击Enter以在新行上创建另一句话,该句子附加了新的li
。用户还可以在句子中强调一些文本(使用按钮,但出于问题而无关(。问题在于,在强调文本后击打输入时,下一个li
也"继承"了重点。如何制作新的li
S香草?
html
<article id="xml" contenteditable="true">
<ol>
<li>hello</li>
<li><em>world</em></li>
</ol>
</article>
CSS
body {
counter-reset: item !important;
}
article#xml ol {
list-style: none;
}
article#xml ol li {
line-height: 1.5;
font-family: sans-serif;
margin-top: 14px;
counter-increment: item;
}
#xml ol li:before {
content: counter(item);
color: #888;
border-right: solid 1px #c4c4c4;
margin-right: 14px;
text-align: center;
font-size: 12px;
display: inline-block;
}
例如。在" Hello"之后添加一个物品会创建一个香草li
,而在"世界"之后这样做时会产生一个强调。
demo
我通过禁用默认浏览器回调并手动实现所有内容来完成此操作。这也解决了我遇到的另一个错误(连续两次输入将删除li
,而不是创建新的错误(。
$('#xml').on('keydown', function(e) {
// 13 is Enter
if(e.keyCode == 13) {
e.preventDefault();
// traverse ancestors till the LI
let oldLi = document.getSelection().anchorNode;
while (oldLi.nodeName != 'LI') {
oldLi = oldLi.parentNode;
}
const newLi = document.createElement('li');
$(oldLi).after(newLi);
// set cursor to the beginning of the new LI
const range = document.createRange();
const sel = window.getSelection();
const newText = document.createTextNode('');
newLi.appendChild(newText);
range.setStart(newText, 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
});
唯一的缺点是光标首先在数字之前移动,并在第一个字符输入后返回其正确位置。
demo
您认为其中之一。
只有第一个样式。
CSS
ol li:first {
....
}
html
<ol>
<li></li> /*styling from the above*/
<li></li> /* NO styling from the above rule */
</ol>
防止样式传播到下一个LI元素
CSS
ol > li {
....
}
html
<ol>
<li> /*styling from the above*/
<li></li> /* NO styling from the above rule*/
</li>
</ol>
知道您可以将它们结合在一起,我只是为了易于插图而展示。所以这也有效。
ol > li: first {
....
}
尝试根据需要申请:
ol li:before {
//only rules for before
}
ol li:first {
//only rules for before
}
ol li {
//rules for all li within ol
}