我的最终目标是让用户能够:
- 从段落中选择文本
- 将文本包裹在一个 span 中
- 在选择的末尾放置一个操作按钮/div,他们可以单击以采取进一步的操作
到目前为止,这是我的代码:
function Discussion(){
var $this = this;
$(document).bind("mouseup",function(){
$this.selectText($this);
});
}
Discussion.prototype.selectText = function($this){
var selection = $this.getSelectedText();
if(selection.length > 3){
console.log(selection);
var spn = '<span class="selected">' + selection + '</span>';
$(this).html($(this).html().replace(selection, spn));
//ERROR here; it says that it can't replace() on undefined $(this).html()
}
}
Discussion.prototype.getSelectedText = function(){
if(window.getSelection){
return window.getSelection().toString();
}
else if(document.getSelection){
return document.getSelection();
}
else if(document.selection){
return document.selection.createRange().text;
}
}
如您所料,到目前为止,我可以使用 window.getSelection().toString()
获取所选内容的文本。如果我删除 .toString()
,我会得到一个 Selection
对象。有了这个,我可以使用 window.getSelection().anchorNode.parentNode
来获取我需要的大部分信息。
我还看到 Selection.anchorOffset
和 Selection.extentOffset
会给我选择的字符范围。有什么方法可以使用此信息来放置跨度?
我想我的问题是:
- 为什么这段代码没有将所选内容包装在 div 中?
- 同一文本的多个实例是否会失败?
- 在用 span 或 inline-block div 或其他东西包装选择后,我是否能够获取(并使用)它的位置来定位额外的按钮/div?
噢,感谢您的宝贵时间!
编辑:我在这里添加了一个 JS fiddle :http://jsfiddle.net/nn62G/
最佳答案
我将在这里发布我的 js fiddle 以及后代的解决方案。感谢大家的帮助!
http://jsfiddle.net/prodikl/mP8KT/
function Discussion(){
var $this = this;
$(document).bind("mouseup",function(){
$this.selectText($this);
});
}
Discussion.prototype.selectText = function($this){
$("mark").contents().unwrap();
$("mark").remove();
var selection = $this.getSelection();
var range = selection.getRangeAt(0);
var cssclass = $(selection.anchorNode.parentNode).attr("class");
if(selection.toString().length > 2){
$this.startPoint = selection.anchorOffset;
$this.endPoint = selection.extentOffset;
var newNode = document.createElement("mark");
range.surroundContents(newNode);
$("mark").attr('title', ' ');
$("mark").tooltip({
content : "<a class='content' href='http://www.google.com' target='_blank'>Here's a link.</a>"
});
$("mark").on('mouseleave',function(event){
event.stopImmediatePropagation();
}).tooltip("open");
}
}
Discussion.prototype.getSelection = function(){
if(window.getSelection){
return window.getSelection();
}
else if(document.getSelection){
return document.getSelection();
}
else if(document.selection){
return document.selection.createRange().text;
}
}
var discussion = new Discussion();
关于javascript - 如何用 span 包装突出显示的文本并在 javascript 中放置一个相对于它定位的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16498877/