JavaScript - 获取 contenteditable div 中插入符号(光标)之前的字母的 CSS 样式

标签 javascript jquery html css

我有 contenteditable div 内容:

<span style="font-weight: 700">S</span>
<span style="font-weight: 100">o</span>
<span style="color: red">m</span>
<span style="text-decoration: underline">e</span>
<span style="background-color: green">T</span>
<span style="text-decoration: line-through">e</span>
<span style="font-style: italic">x</span>
<span style="font-family: Arial">t</span>

我想获取插入符(光标)之前的元素样式。例如,如果我在 SomeText 之间有插入符号,我想得到 text-decoration: underline。我的代码在下面(有效,但我得到了最后一个元素的样式(font-family: Arial))。我该如何使用 JavaScript 或/和 JQuery 修复它?
感谢帮助。

$('button').click(function() {
  var style = $('#Box span').last().attr('style');
  $('#Result').text('Result: ' + style);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="Box" contenteditable="true">
  <span style="font-weight: 700">S</span><span style="font-weight: 100">o</span><span style="color: red">m</span><span style="text-decoration: underline">e</span><span style="background-color: green">T</span><span style="text-decoration: line-through">e</span><span style="font-style: italic">x</span><span style="font-family: Arial">t</span>
</div>

<button>Get result</button>
<p id="Result"></p>

最佳答案

请看下面的代码。这可以输出在光标旁边的元素上声明的样式。

$('button').click(function() {
  var selection = null;
  if (window.getSelection) {
    selection = window.getSelection();
  } else if (document.selection && document.selection.type != "Control") {
    selection = document.selection;
  }
  
  if(selection && selection.anchorNode && selection.anchorNode.parentNode) {
    var style = selection.anchorNode.parentNode.style.cssText;
    $('#Result').text('Result: ' + style);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="Box" contenteditable="true"><span style="font-weight: 700">S</span><span style="font-weight: 100">o</span><span style="color: red">m</span><span style="text-decoration: underline">e</span><span style="background-color: green">T</span><span style="text-decoration: line-through">e</span><span style="font-style: italic">x</span><span style="font-family: Arial">t</span></div>

<button>Get result</button>
<p id="Result"></p>

关于JavaScript - 获取 contenteditable div 中插入符号(光标)之前的字母的 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45863147/

相关文章:

javascript - 无需在d3.js中使用selectAll即可忽略第一个数据

php - 在PHP和MySql中创建一个累积比较表

css - 定位元素的同级子元素

javascript - 使用 jQuery/JS 在全屏上查看所有选择选项

python - 从一组 URL 下载单独的图像

javascript - 带有 dotenv 和 TypeScript 的环境变量

javascript - jQuery 按时间间隔单击各个元素

javascript - 应用脚本 : open PDF right after creation

javascript - jQuery noConflict IE 问题

javascript - 使用相同数据延迟对相同 URL 的 Ajax 调用