javascript - JS Contenteditable 下划线不起作用

标签 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 内单击,然后按下划线按钮
  2. 现在输入一个单词或一个字母
  3. 然后按退格键并删除您输入的任何内容。
  4. 现在再次按下划线按钮
  5. 开始输入内容
  6. 您输入的单词仍带有下划线

理想情况下,再次单击下划线按钮应该会删除您输入的单词的下划线格式,但由于某种原因,它不会。

我不明白为什么会这样。它可以很好地处理粗体斜体,但是对于下划线,它会搞乱并保持格式。

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

最佳答案

当您单击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>

现在向用户提供视觉指示,表明他是否可以使用下划线按钮。

关于javascript - JS Contenteditable 下划线不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029340/

相关文章:

javascript - textarea的容量

javascript - 页面完全加载后关闭窗口

javascript - ajax帖子作弊预防

javascript - jquery dragtable 动态添加的列拖动选项不起作用

jquery - 使用 jQuery Sortables 拖动项目时单选按钮被取消选择

html - 如何让一列定义表格的高度而另一列总是有滚动条?

javascript - 有没有办法在 Three.js 中制作小 Canvas ?

javascript - 上传后如何在弹出窗口中显示图像?

javascript - 如果用户同时发送多张照片,如何让机器人响应一次?

php - 存储用户在文本中输入的超链接