简体   繁体   English

jQuery包围带有span标签的所选文本和图像

[英]jquery surround selected text and image with span tag

I want to surround selected text and image or texts with multiple tags with span tag in jquery. 我想在jquery中用span标签包围所选文本和图像或具有多个标签的文本。 How can i achieve that, I have seen many examples like the below jsfiddle code. 我如何实现这一目标,我已经看到了许多类似下面的jsfiddle代码的示例。 All the examples are done only with text, but now want to surround both text and image with span tag. 所有示例仅使用文本完成,但是现在希望使用span标签将文本和图像都包围起来。 Thanks in advance 提前致谢

$(document).ready(function(){
$('.format').click(function(){
    var highlight = window.getSelection(),  
    spn = '<span class="highlight">' + highlight + '</span>',
    text = $('.conttext').text(),
    range = highlight.getRangeAt(0),
    startText = text.substring(0, range.startOffset), 
    endText = text.substring(range.endOffset, text.length);

    $('.conttext').html(startText + spn + endText);
});
});

JSFiddle 的jsfiddle

Change your code to use the surroundContents method of the range. 更改您的代码以使用范围的surroundContents方法

$('.format').click(function () {
    var highlight = window.getSelection(),
        spn = $('<span class="highlight" />')[0],
        range = highlight.getRangeAt(0);

    range.surroundContents(spn);
});

Demo at http://jsfiddle.net/gaby/BGKSN/181 演示位于http://jsfiddle.net/gaby/BGKSN/181
Demo with image at http://jsfiddle.net/gaby/BGKSN/182/ 带有图片的演示位于http://jsfiddle.net/gaby/BGKSN/182/

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

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