javascript – JS:获取contentEditable div中所有选定节点的数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – JS:获取contentEditable div中所有选定节点的数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2253字,纯文字阅读大概需要4分钟。
内容图文
![javascript – JS:获取contentEditable div中所有选定节点的数组](/upload/InfoBanner/zyjiaocheng/714/2c86d9efabce418ea9ea8e11ee0fcacd.jpg)
嗨,我一直在使用contentEditable一段时间了,我觉得我对它有很好的处理.回避我的一件事是如何获得部分或完全在用户选择范围内的所有节点的引用数组.有人有个主意吗?
这是从一开始:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function getSelectedNodes(){
var sel = window.getSelection();
try{var frag=sel.getRangeAt(0).cloneContents()}catch(e){return(false);}
var tempspan = document.createElement("span");
tempspan.appendChild(frag);
var selnodes = Array() //<<- how do I fill this array??
var output = ''
for(i in selnodes){
output += "A "+selnodes[i].tagName+" was found\n"
//do something cool with each element here...
}
return(output)
}
</script>
</head>
<body contentEditable="true" onkeypress="return(keypress(event))">
<div>This <strong>div</strong> is <em>content</em> <span class='red'>editable</span> and has a couple of <em><strong>child nodes</strong></em> within it</div>
<br />
<br />
<a href="#" onm ouseover="alert(getSelectedNodes())">hover here</a>
</body>
</html>
解决方法:
这是一个版本,它为您提供实际选定和部分选择的节点而不是克隆.或者你可以使用我的Rangy库,它有一个Range对象的getNodes()方法,可以在IE< 9.
function nextNode(node) {
if (node.hasChildNodes()) {
return node.firstChild;
} else {
while (node && !node.nextSibling) {
node = node.parentNode;
}
if (!node) {
return null;
}
return node.nextSibling;
}
}
function getRangeSelectedNodes(range) {
var node = range.startContainer;
var endNode = range.endContainer;
// Special case for a range that is contained within a single node
if (node == endNode) {
return [node];
}
// Iterate nodes until we hit the end container
var rangeNodes = [];
while (node && node != endNode) {
rangeNodes.push( node = nextNode(node) );
}
// Add partially selected nodes at the start of the range
node = range.startContainer;
while (node && node != range.commonAncestorContainer) {
rangeNodes.unshift(node);
node = node.parentNode;
}
return rangeNodes;
}
function getSelectedNodes() {
if (window.getSelection) {
var sel = window.getSelection();
if (!sel.isCollapsed) {
return getRangeSelectedNodes(sel.getRangeAt(0));
}
}
return [];
}
内容总结
以上是互联网集市为您收集整理的javascript – JS:获取contentEditable div中所有选定节点的数组全部内容,希望文章能够帮你解决javascript – JS:获取contentEditable div中所有选定节点的数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。