Javascript 获取所选文本开头(和结尾)的父元素
假设我有这个HTMLJavascript 获取所选文本开头(和结尾)的父元素,javascript,jquery,Javascript,Jquery,假设我有这个HTML <div id="someparent"> Foo <span id="one">Selection starts anywhere inside here</span> <span id="two">Selection ends anywhere inside here</span> <span id="three">Some more text here<
<div id="someparent">
Foo
<span id="one">Selection starts anywhere inside here</span>
<span id="two">Selection ends anywhere inside here</span>
<span id="three">Some more text here</span>
Bar
</div>
福
选择从这里的任何地方开始
选择在这里的任何地方结束
这里有更多的文字
酒吧
我想返回span#一个
,和span#两个
节点(这样我可以在它们周围再加一个span*)。如果foo和bar是选择的起点和终点,那么将返回div#someparent
(两次)
*即使使用jQuery,如何做到这一点也会很有帮助
这类似于 我想你可以用这个范围来做
$(“按钮”)。单击(函数(){
var selection=document.getSelection();
var start=selection.getRangeAt(0);
log('start:'+start.startContainer.parentNode.id);
log('end:'+start.endContainer.parentNode.id);
})
福
选择从这里的任何地方开始
选择在这里的任何地方结束
此处有更多文本[在此处输入链接说明][1]
酒吧
测试
我想你可以用这个范围来做
$(“按钮”)。单击(函数(){
var selection=document.getSelection();
var start=selection.getRangeAt(0);
log('start:'+start.startContainer.parentNode.id);
log('end:'+start.endContainer.parentNode.id);
})
福
选择从这里的任何地方开始
选择在这里的任何地方结束
此处有更多文本[在此处输入链接说明][1]
酒吧
test
此代码将返回选择开始和结束的父节点:
var getSelectionParents=function(){
var selection=document.getSelection();
if(!selection.toString().length)
return false;
else
return {
start:selection.anchorNode.parentNode,
end:selection.focusNode.parentNode
};
}
document.addEventListener('mouseup',function(){
console.log(getSelectionParents());
});
下面是一段正在运行的代码:。此代码将返回选择的开始和结束的父节点:
var getSelectionParents=function(){
var selection=document.getSelection();
if(!selection.toString().length)
return false;
else
return {
start:selection.anchorNode.parentNode,
end:selection.focusNode.parentNode
};
}
document.addEventListener('mouseup',function(){
console.log(getSelectionParents());
});
下面是一些正在运行的代码:。这似乎工作得很好。是跨浏览器的吗?它在IE中工作吗?(我不担心支持旧版本,主要是IE9和更高版本)。是的,我刚刚测试了我在IE9和IE11中提供的JSFIDLE,它似乎在这两个版本中都能工作。如果您愿意的话,这里有一个后续问题:-)这似乎工作得很好。是跨浏览器的吗?它在IE中工作吗?(我不担心支持旧版本,主要是IE9和更高版本)。是的,我刚刚测试了我在IE9和IE11中提供的JSFIDLE,它似乎在这两个版本中都能工作。如果您愿意,这里有一个后续问题:-)