Javascript 在设计模式中将所选文本指定给变量

Javascript 在设计模式中将所选文本指定给变量,javascript,wysiwyg,designmode,Javascript,Wysiwyg,Designmode,我有一段代码,将文档设置为designMode,然后使用document.execCommand()函数对所选文本进行操作 它提供了各种功能——例如,它允许用户将选定的文本行转换为粗体或斜体(基本上就是我现在正在输入的文本编辑器的功能) 下面是代码的简化示例: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <d

我有一段代码,将文档设置为designMode,然后使用document.execCommand()函数对所选文本进行操作

它提供了各种功能——例如,它允许用户将选定的文本行转换为粗体或斜体(基本上就是我现在正在输入的文本编辑器的功能)

下面是代码的简化示例:

<!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>
是这样,还是有更好的方法


如何获取相关选定文本并将其分配给变量?

您需要多做一点努力。还需要使用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>

这是一些文字-突出显示其中的一部分,然后按h1,然后按li
这是一些其他文字-突出显示其中的一部分,然后按h1,然后按li
h1
锂
document.designMode='on';
setInterval(函数(){
var el=getSelectionContainerElement();
如果($(el).is('h1')){
$(“#li”).attr(“残疾”,真实);
}
其他的
{
$(“#li”).attr(“禁用”,假);
}
}, 100);
函数setToHeader(){
document.execCommand('formatBlock',false,'h1');
}
函数setToList(){
document.execCommand('insertunderedList',false,null);
}
函数getSelectionContainerElement(){
var范围、sel、容器;
if(document.selection&&document.selection.createRange){
//IE案例
range=document.selection.createRange();
返回范围.parentElement();
}else if(window.getSelection){
sel=window.getSelection();
如果(选择getRangeAt){
如果(选择范围计数>0){
范围=选择范围(0);
}
}否则{
//旧WebKit选择对象没有getRangeAt,因此
//从其他选择属性创建范围
range=document.createRange();
范围设置开始(选择锚定节点、选择锚定偏移);
范围设置结束(选择聚焦节点,选择聚焦偏移);
//处理向后选择所选内容时的情况(从文档的末尾到开头)
如果(range.collapsed!==sel.isCollapsed){
范围设置开始(选择聚焦模式、选择聚焦偏移);
设置范围(选择锚定节点,选择锚定偏移);
}
}
如果(范围){
容器=range.commonAncestorContainer;
//检查容器是否为文本节点,如果是,则返回其父节点
return container.nodeType==3?container.parentNode:容器;
}   
}
}

您可以使用选择对象获取所选文本

e、 g.在IE11中:

getSelection()
完整文档可在此处找到:

 https://msdn.microsoft.com/en-us/library/ms535869(v=vs.85).aspx

不幸的是,这不起作用。我的第一个想法是类似的,但在实际代码中,用户正在编辑一个文本字段——WYSIWIG编辑器。这意味着他们可以将一行切换到h1,然后按return,下一行是a。我不想在下一行禁用按钮。因此,我需要检查光标所在的实际行,或所选文本,以决定是否为给定的选定文本片段启用或禁用按钮。您可以使用以下函数获取选定文本:函数getSelectionText(){var text=”“;if(window.getSelection){text=window.getSelection().toString();}否则如果(document.selection&&document.selection.type!=“Control”){text=document.selection.createRange().text;}返回text;}。但是,我相信它不是您需要的文本,而是如果它被包装在标记中。我说得对吗?
 https://msdn.microsoft.com/en-us/library/ms535869(v=vs.85).aspx