我正在一个书签应用程序,我必须存储用户选择的关键字或单词或内容.我正在使用createRange()和addRange()
javascript方法创建范围,然后由用户查找所选元素/内容.我为此编写的代码如下.
<head> <script type="text/javascript"> var storedSelections = []; function StoreSelection () { if (window.getSelection) { var currSelection = window.getSelection (); for (var i = 0; i < currSelection.rangeCount; i++) { storedSelections.push (currSelection.getRangeAt (i)); } currSelection.removeAllRanges (); } else { alert ("Your browser does not support this example!"); } } function ClearStoredSelections () { storedSelections.splice (0,storedSelections.length); } function ShowStoredSelections () { if (window.getSelection) { var currSelection = window.getSelection (); currSelection.removeAllRanges (); for (var i = 0; i < storedSelections.length; i++) { currSelection.addRange (storedSelections[i]); } } else { alert ("Your browser does not support this example!"); } } </script> </head> <body> Select some content on this page and use the buttons below.<br /> <br /> <button onclick="StoreSelection ();">Store the selection</button> <button onclick="ClearStoredSelections ();">Clear stored selections </button> <button onclick="ShowStoredSelections ();">Show stored selections</button> </body>
这个代码在Firefox上运行正常.我能够逐个选择多个东西,并能够再次显示所选内容,但是在铬和铬上我不断支持不连续的选择.当我在范围数组中存储多个元素并单击显示存储的选择按钮时出现错误.
帮助将不胜感激请建议我,如果还有其他替代方案,可以完成这个书签任务.
解决方法
写
window.getSelection().removeAllRanges();
在创建范围之前.
https://bugs.chromium.org/p/chromium/issues/detail?id=399791