我有 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>
我想获取插入符(光标)之前的元素样式。例如,如果我在 Some
和 Text
之间有插入符号,我想得到 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/