Cru*_*inh 18 javascript safari webkit textselection
我有以下非常简单的html页面:
<html>
<head>
<script type="text/javascript">
function alertSelection()
{
var selection = window.getSelection();
var txt = selection.toString();
alert(txt);
}
</script>
</head>
<body>
This is <span style="background-color:black;color:white">the</span> text.
<div style="background-color:green;width:30px;height:30px;margin:30px"
onmouseover="alertSelection()">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我选择整个第一行并将鼠标悬停在方格上时,我会收到"这是文本"的警报.
我如何解决此问题,以便不会从警报消息中删除span标记或任何其他选定的HTML?
编辑:我正在寻找如何从中获取完整的HTML window.getSelection().警报对话框就是我试图验证代码的方式.我只关心在Safari中工作.
Tim*_*own 62
这是一个函数,它将为您提供与所有主流浏览器中当前选择相对应的HTML:
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
alert(getSelectionHtml());
Run Code Online (Sandbox Code Playgroud)
Chr*_*rey 10
使用Rangy:https://github.com/timdown/rangy
跨浏览器范围和选择库.
在这里查看演示:http://rangy.googlecode.com/svn/trunk/demos/index.html
| 归档时间: |
|
| 查看次数: |
12283 次 |
| 最近记录: |