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 contenteditable 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.
推荐答案
DEMO: 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屋!
查看全文