当文档上的某些文本突出显示时,只要单击文档,默认的浏览器突出显示就会丢失.
我想保持浏览器的亮点,就像apture http://www.apture.com/一样.突出显示一些文字,它会弹出一个"了解更多"的泡泡,点击"了解更多"按钮,它仍然不会失去默认的浏览器高亮焦点.
我怎么做?
我基本上想要获得所选文本的位置而不添加跨度并在单击按钮时保持浏览器高亮显示.
这是一个简单的示例,说明如何在用户单击特定元素时保留选择.它在元素的情况下存储选择Range或TextRange(IE <= 8)并在mousedown事件中重新选择这些范围mouseup.
<script type="text/javascript">
var saveSelection, restoreSelection;
if (window.getSelection) {
// IE 9 and non-IE
saveSelection = function() {
var sel = window.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
restoreSelection = function(savedSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSelection.length; i < len; ++i) {
sel.addRange(savedSelection[i]);
}
};
} else if (document.selection && document.selection.createRange) {
// IE <= 8
saveSelection = function() {
var sel = document.selection;
return (sel.type != "None") ? sel.createRange() : null;
};
restoreSelection = function(savedSelection) {
if (savedSelection) {
savedSelection.select();
}
};
}
window.onload = function() {
var specialDiv = document.getElementById("special");
var savedSel = null;
specialDiv.onmousedown = function() {
savedSel = saveSelection();
};
specialDiv.onmouseup = function() {
restoreSelection(savedSel);
};
};
</script>
<p>
Select something up here and click on one of the areas below.
<b>The first will lose the selection</b>, while the second will keep it.
</p>
<div style="border: solid blue 1px">Normal div</div>
<div id="special" style="border: solid blue 1px">Special div.
Press me and keep the selection</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3666 次 |
| 最近记录: |