简体   繁体   English

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

[英]window.getSelection add class to selection with jquery

I want to select an image and a add a class name to the selection.我想选择一个图像并将一个类名添加到选择中。 using window.getSelection .使用window.getSelection


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


<input type='button' onclick='addClassName();' value='addClassName'/>

To add class to selection, you need to wrap it with <span> other wise it will not work.要将类添加到选择中,您需要用<span>包装它,否则它将不起作用。 Here's the solution.这是解决方案。

    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>');

    }
    }

This should guide you in the proper direction.这应该会引导您朝着正确的方向前进。 Modify it as you see fit.按照您认为合适的方式对其进行修改。

Check working example at http://jsfiddle.net/wP8w9/2/http://jsfiddle.net/wP8w9/2/检查工作示例

$(sel).find('img').addClass('myClass');

This will take the selection, turn it into a jQuery object, find the image, and add a class to it.这将获取所选内容,将其转换为 jQuery 对象,找到图像并为其添加一个类。

I have not tested this.我没有测试过这个。

if you want to use javascript you can do:如果你想使用 javascript,你可以这样做:

function addClassName() {
     $('img').addClass('newClass') // adds the class 'newClass' to all image objects
}


<input type='button' onclick='addClassName();' value='addClassName'/>

you can use any selector aside from 'img' in that function as well您也可以在该函数中使用除“img”之外的任何选择器

var sel= window.getSelection().getRangeAt(0);

$(sel).addClass("someClass");

window.getSelection() will give you the selection, but not the current (or highlighted) selection. window.getSelection()将为您提供选择,但不是当前(或突出显示)的选择。 You need to use the selection's getRangeAt method for that您需要为此使用选择的 getRangeAt 方法

获取所选文本的类别

window.getSelection().baseNode.parentElement.className

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

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