我有一段代码,它将文档设置为designMode,然后使用document.excCommand()函数对所选文本进行操作。
它提供了各种功能——例如,它允许用户将选定的文本行变成粗体或斜体(本质上是我现在正在键入的文本编辑器的功能)。
以下是代码的简化示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
This is some text - highlight a section of it and press h1 then li
</div>
<button onclick="setToHeader()" id="h1" style="width:100px" unselectable="on">h1</button>
<button onclick="setToList()" id="li" style="width:100px" unselectable="on">li</button>
<script>
document.designMode = 'on';
function setToHeader() {
document.execCommand('formatBlock', false, 'h1');
}
function setToList() {
document.execCommand('insertUnorderedList', false, null);
}
</script>
</body>
</html>
我的问题是,我不想使用li按钮,也就是说,当选择的文本已经用h1按钮转换为标题格式时,将其转换为列表格式。
我想我想能够阅读所选的文本,并简单地用之类的东西进行检查
// var selectedText = ???
var isHeading = selectedText.search('h1') > -1
是这样,还是有更好的方法?
如何获取相关的选定文本并将其分配给变量?
您可以使用选择对象获取所选文本。
例如在IE11:中
getSelection()
完整的文档可以在这里找到:
https://msdn.microsoft.com/en-us/library/ms535869(v=vs.85).aspx
您需要付出更多的努力。还需要使用jquery,请查看:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>This is some text - highlight a section of it and press h1 then li </div>
<div>This is some other text - highlight a section of it and press h1 then li </div>
<button onclick="setToHeader()" id="h1" style="width:100px" unselectable="on">h1</button>
<button onclick="setToList()" id="li" style="width:100px" unselectable="on">li</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
document.designMode = 'on';
setInterval(function () {
var el = getSelectionContainerElement();
if($(el).is('h1')){
$("#li").attr("disabled", true);
}
else
{
$("#li").attr("disabled", false);
}
}, 100);
function setToHeader() {
document.execCommand('formatBlock', false, 'h1');
}
function setToList() {
document.execCommand('insertUnorderedList', false, null);
}
function getSelectionContainerElement() {
var range, sel, container;
if (document.selection && document.selection.createRange) {
// IE case
range = document.selection.createRange();
return range.parentElement();
} else if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
} else {
// Old WebKit selection object has no getRangeAt, so
// create a range from other selection properties
range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the document)
if (range.collapsed !== sel.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
}
if (range) {
container = range.commonAncestorContainer;
// Check if the container is a text node and return its parent if so
return container.nodeType === 3 ? container.parentNode : container;
}
}
}
</script>
</body>
</html>