如何获取所选文本上返回的文本和html

How to get the text and html returned on selected text

本文关键字:文本 返回 html 何获取 获取      更新时间:2023-09-26

所以我在我的网站上使用了一个编辑工具,并在工具栏中添加了我自己的按钮和自定义样式。我有一个在样式之间切换并获取选定文本的功能。如何创建一个函数,从所选文本中获取html并找到某个元素,如<p>或<img>?

这就是我目前所拥有的。。。

init: function( editor ) {
    var config = editor.config,
        lang = editor.lang.format;
    // Gets the list of tags from the settings.
    var tags = []; //new Array();
    tags[0]=["red_font", "Red Font", "Name"];
    // Create style objects for all defined styles.
    editor.ui.addRichCombo( 'dag_wygwam',
        {
            label : "Buttons",
            title :"Buttons",
            voiceLabel : "Buttons",
            className : 'cke_format',
            multiSelect : false,
            panel :
            {
                voiceLabel : lang.panelVoiceLabel
            },
            init : function()
            {
                this.startGroup( "Buttons Functions" );
                for (var this_tag in tags){
                    this.add(tags[this_tag][0];
                }
            },
            onClick : function( value )
            {
                console.log(editor.getSelection().getSelectedText());
                editor.fire( 'saveSnapshot' );
                switch (value) {
                    case "red_font": value = red_font(editor.getSelection().getSelectedText()); break;
                }                      
               editor.insertHtml(value);
                editor.fire( 'saveSnapshot' );                        
            }
        });
}
});
function red_font(selection){
}

因此,这个red_font函数必须执行以下操作:从所选文本中提取html,在所选文本内找到span类,并仅使span元素为红色。

var theselectedtext = null;
var theselectedelement = null;
document.onmouseup = function(e) {
e = e||event;
// to get the selected text
if (window.getSelection) {
// most browsers
theselectedtext = window.getSelection().toString();
} else {
// IE9
if (document.selection.createRange) {
theselectedtext = document.selection.createRange().text;
}
}
if (theselectedtext != null) {
// get the last clicked element
theselectedelement = e.target.tagName.toLowerCase();
}
}

在任何给定时间,selectedtext变量将包含所选文本,selectedElement变量将包含选定元素。