简体   繁体   English

在contentEditable div中粗体选择文本,使用没有jQuery等库的纯JavaScript

[英]Bold Selected Text in contentEditable div, using pure JavaScript without libraries such as jQuery

We have an editable div and we want to change the style of the text, selected by the user, on clicking our button; 我们有一个可编辑的div,我们希望在点击我们的按钮时改变用户选择的文本样式; just same as this editor's bold or italic button. 与此编辑器的粗体或斜体按钮相同。

But when we click on the button our selected text get deselected. 但是当我们点击按钮时,我们选择的文本被取消选中。

So how to keep our selected text highlighted even if the focus from the editable is off and change the style. 因此,即使来自可编辑的焦点关闭并更改样式,如何突出显示所选文本。

My Code : 我的代码:

Editable Div: 可编辑的Div:

var textbox= document.createElement("div");
textbox.setAttribute("contenteditable", "true");

Button : 按钮:

var bold = document.createElement("div");
bold.innerHTML = "B";

Button Click: 按钮单击:

bold.addEventListener("click", function(){
        getSelectedText();
},false);

    function getSelectedText()
    {
       var html = "";
       if (window.getSelection) {
         html = window.getSelection().toString();
       } 

       else if (document.selection && document.selection.type != "Control") {
            html = document.selection.createRange().text;
       }
       alert(html);
    }

You can get the selection by listening to your contentEditable 's onmouseup and store it in a variable. 您可以通过监听contentEditableonmouseup来获取选择,并将其存储在变量中。 After you clicked a div, you restore the selection to back what it was: 单击div后,将恢复选择以恢复它的内容:

Javascript: 使用Javascript:

var range = "";

function getSelected() {
    var selection = window.getSelection()
    range = selection.getRangeAt(0);
}

function reselect() {
    var selection = window.getSelection();  
    selection.removeAllRanges();
    selection.addRange(range);
}

jsfiddle DEMO jsfiddle DEMO
used a button and a div for buttons so you can see the difference. 使用按钮和div按钮,这样你就可以看到差异。

Either use the mousedown event instead of the click event or set the <div> button to be unselectable. 使用mousedown事件而不是click事件或将<div>按钮设置为不可选。

See this answer for details. 有关详情,请参阅此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM