window.getSelection使用jquery将类添加到选择中

Zeb*_*bra 3 html javascript jquery dom execcommand

我想选择一个图像并为选择添加一个类名.使用window.getSelection.


function addClassName() {
     var sel = window.getSelection();
     //what goes here???
}


<input type='button' onclick='addClassName();' value='addClassName'/>
Run Code Online (Sandbox Code Playgroud)

Hus*_*ein 6

要将类添加到选择中,您需要使用<span>其他方式将其包装起来,它将无效.这是解决方案.

    function addClassToSelection(){
    var sel = window.getSelection ? window.getSelection() : document.selection.createRange(); // FF : IE
    if(sel.getRangeAt){ // thats for FF
    var range = sel.getRangeAt(0);
    var newNode = document.createElement("span");
    newNode.setAttribute('class', 'someclass');
    range.surroundContents(newNode);
    } else { //and thats for IE7
    sel.pasteHTML('<span class="someclass">'+sel.htmlText+'</span>');

    }
    }
Run Code Online (Sandbox Code Playgroud)

这应该指导您正确的方向.根据需要修改它.

查看http://jsfiddle.net/wP8w9/2/上的工作示例