SurroundContents() 使更改“实时”吗?
所以这个函数:
function symbolize(e){
var elements = e.childNodes; // text nodes are necessary!
console.log(elements);
for(var i=0; i < elements.length; i++){
t = elements[i];
var range = document.createRange(), offset = 0, length = t.nodeValue.length;
while(offset < length){
range.setStart(t, offset); range.setEnd(t, offset + 1);
range.surroundContents(document.createElement('symbol'));
offset++;
}
}
}
..应该迭代每个字母并将其包装在
元素中。但它似乎不起作用。
因此,我在获取 *.childNodes
之后添加了 console.log();
,但正如您在上面的示例站点中看到的那样,日志包含 2数组前面(!)出现意外的元素。是的,正因为如此,我有一种感觉 surroundContents();
使更改生效(!)。 无法找到任何相关参考
其中一个元素是空的 Text
节点,另一个是我的
。但是,是的,这完全是意想不到的结果,并且扰乱了函数的其余部分。
这可能有什么问题吗?
提前致谢!
更新
哦,看来Chrome上添加了元素,Firefox没有添加元素,但仍然停止了该功能。
Links to live examples @ jsfiddle & jsbin.
So this function:
function symbolize(e){
var elements = e.childNodes; // text nodes are necessary!
console.log(elements);
for(var i=0; i < elements.length; i++){
t = elements[i];
var range = document.createRange(), offset = 0, length = t.nodeValue.length;
while(offset < length){
range.setStart(t, offset); range.setEnd(t, offset + 1);
range.surroundContents(document.createElement('symbol'));
offset++;
}
}
}
..should iterate over every letter and wrap it in a <symbol/>
element. But it doesn't seem to be working.
So I added the console.log();
right after the *.childNodes
have been fetched, but as you'll see in the example site above, the log contains 2 unexpected elements in front(!) of the array. And yeah, because of this, I have a feeling that surroundContents();
make the changes live(!). couldn't find any reference on this though
One of the elements is an empty Text
node, the other is my <symbol/>
. But yeah, this is totally unexpected result and messes up the rest of the function.
What could be wrong with it?
Thanks in advance!
Update
Oh, looks like the elements are added on Chrome, Firefox doesn't add the elements, but still halts the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Element.childNodes 确实是一个活动列表,否则不可能是这样(这意味着节点列表不正确)。最简单的解决方案是在弄乱它之前冻结(复制)它(通过围绕现有范围)。
https://developer.mozilla.org/en/childNodes 它的类型为 NodeList
https://developer.mozilla.org/En/DOM/NodeList 这些是实时列表
Element.childNodes is indeed a live list , it could not be otherwise (that would mean an incorrect list of nodes). The easiest solution is to freeze (make a copy of) it before you mess with it (by surrounding existing ranges).
https://developer.mozilla.org/en/childNodes it's of type NodeList
https://developer.mozilla.org/En/DOM/NodeList those are live lists