jQuery用SPAN环绕突出显示的文本 [英] jQuery surround highlighted text with SPAN
本文介绍了jQuery用SPAN环绕突出显示的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码应该在给定的Div中用跨度将突出显示的文本括起来.
The following code is supposed to surround the highlighted text in a given Div with a span.
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection();
var spn = '<span class="highlight">' + highlight + '</span>';
$('.conttext').content().replace(highlight, spn);
});
});
这种性质的功能可用于为HTML内容可编辑的DIV提供格式化选项.
A function of this nature could be used to provide formating options to an HTML contenteditable DIV.
某些事情显然是错误的,尽管目前尚无法解决.
Something is clearly wrong though as it does not currently work.
推荐答案
演示: http://jsfiddle.net/BGKSN/24/
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection();
var spn = '<span class="highlight">' + highlight + '</span>';
var text = $('.conttext').text();
$('.conttext').html(text.replace(highlight, spn));
});
});
稍后编辑:
基于注释,这是实际的功能示例:
Based on the comment, this is the real functional example:
$(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);
});
});
文档: https://developer.mozilla. org/en-US/docs/Web/API/window.getSelection
这篇关于jQuery用SPAN环绕突出显示的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文