JS Contenteditable下划线不起作用

时间:2018-08-26 18:52:22

标签: javascript jquery html contenteditable execcommand

我只是在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>

要重新创建该错误:

  1. contenteditable div内单击,然后按underline button
  2. 现在输入单词或字母
  3. 然后按backspace并删除您键入的任何内容。
  4. 现在再次按下underline button
  5. 开始输入内容
  6. 您输入的单词仍带有下划线

理想情况下,再次单击underline button应该会删除您键入的单词的下划线格式,但是由于某种原因,它并没有。

我不明白为什么会这样。它可以与bolditalics一起正常工作,但与underline一起使用时,它会弄乱并保持格式。

如果有人可以提供解决方法或可以解决此问题的方法,我将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

当您单击underline按钮时,«下划线将打开或关闭所选内容或在插入点。»

documentation

现在,当您退格直到没有更多字符并且blur可编辑div时,插入的<u>标记将被删除。再次单击该按钮,然后将其再次打开。

在您自己的代码段中尝试以下操作:

  1. contenteditable div内单击,然后按underline button
  2. 现在输入单词或字母
  3. 然后按backspace并删除您键入的任何内容。
  4. 现在只需模糊可编辑字段并再次聚焦。
  5. 开始输入内容
  6. 您键入的单词不是没有带下划线

因此,我建议您确保进行选择以启用下划线按钮...因此,仅对选择的内容应用下划线...防止在插入点应用下划线«的可能性»,这对用户来说并不明显...

$("[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>

现在,用户可以看到视觉效果,好像他可以使用下划线按钮一样。