我认为我刚刚在 document.execCommand
中遇到了一个错误。问题就在这里。
$("#underline-btn").click(function() {
document.execCommand("underline");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">This is a contenteditable div. To recreate the bug, click inside this div and press the underline button. Now type a word or a letter. Then press backspace and delete whatever you typed. Now press the underline button again. Start typing something. The word you type will still be underlined.</div>
<button id="underline-btn">Underline</button>
重现错误:
- 在
contenteditable
div
内单击,然后按下划线按钮
- 现在输入一个单词或一个字母
- 然后按
退格键
并删除您输入的任何内容。 - 现在再次按
下划线按钮
- 开始输入内容
- 您输入的单词仍带有下划线
理想情况下,再次单击下划线按钮
应该会删除您输入的单词的下划线格式,但由于某种原因,它不会。
我不明白为什么会这样。它可以很好地处理粗体
和斜体
,但是对于下划线
,它会搞乱并保持格式。
如果有人可以提供解决方法或解决此问题的方法,我将不胜感激。谢谢。
最佳答案
当您单击underline
时按钮,«下划线在选择或插入点处打开/关闭。»
现在,当您退格直到没有更多字符时,blur
可编辑的div,插入<u>
标签被删除。再次单击该按钮将再次打开它。
在您自己的代码片段中尝试一下:
- 点击
contenteditable
内部div
然后按underline button
- 现在输入一个单词或一个字母
- 然后按
backspace
并删除您输入的任何内容。 - 现在只需模糊可编辑字段并再次聚焦即可。
- 开始输入内容
- 您输入的单词没有下划线
所以我建议您确保选择启用下划线按钮...因此下划线只会应用于所做的选择...防止在插入点应用下划线«的可能性»,这对用户来说并不明显......
$("[contenteditable]").on("mouseup",function(){
selectionMade = (window.getSelection().type == "Range"); // True is there actually is a selection made.
$("#underline-btn").prop("disabled",!selectionMade);
});
$("#underline-btn").click(function() {
document.execCommand("underline");
console.log("Toggled underline on a selection.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">This is a contenteditable div. To recreate the bug, click inside this div and press the underline button. Now type a word or a letter. Then press backspace and delete whatever you typed. Now press the underline button again. Start typing something. The word you type will still be underlined.</div>
<button id="underline-btn" disabled>Underline</button>
现在向用户提供视觉指示,表明他是否可以使用下划线按钮。
关于javascript - JS Contenteditable 下划线不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029340/