我可以在客户端使用 JavaScript 创建类似于 Internet Explorer 加速器的东西吗?
当用户在页面上选择一些文本时,我希望显示一个可点击的图标。
我应该等待什么事件?
我可以在客户端使用 JavaScript 创建类似于 Internet Explorer 加速器的东西吗?
当用户在页面上选择一些文本时,我希望显示一个可点击的图标。
我应该等待什么事件?
本质上,这个想法是document.onmouseup
适当地处理事件,显示隐藏的“加速器”div
并检索选定的文本。
我想以下示例对您来说将是一个很好的起点:
<html>
<head>
<script>
function getSelectedText() {
var selection = '';
if (window.getSelection) selection = window.getSelection().toString();
else if (document.getSelection) selection = document.getSelection();
else if (document.selection) selection = document.selection.createRange().text;
return selection;
}
function showAccelerator(x, y){
var text = getSelectedText();
if (text !== ''){
accelerator.style.display = '';
accelerator.style.left = x;
accelerator.style.top = y;
timeout_id = setTimeout(hideAccelerator, 1000);
} else {
hideAccelerator()
}
}
function hideAccelerator(){
clearTimeout(timeout_id);
accelerator.style.display='none';
}
function isAcceleratorHidden(){
return accelerator.style.display === 'none';
}
function onMouseUp(evt){
if (isAcceleratorHidden()){
var event2 = (document.all) ? window.event : evt;
showAccelerator(event2.clientX, event2.clientY);
}
}
function alertSelection(){
alert(getSelectedText());
}
document.onmouseup = onMouseUp;
</script>
</head>
<body>
<div id="accelerator" style="position: absolute; width: 100px; left: 0px; top: -50px; display: none; border: solid; background-color : #ccc;">
accelerator div<input type="button" value="alert" onclick="alertSelection();" />
</div>
<p>
sometext<br/><br/><br/>
even more text
</p>
</body>
</html>
可能最好的方法是在页面上设置一个mouseup侦听器,该侦听器调用一个测试选择的函数,例如
function hasSelection() {
var selText = "";
if (document.selection) { // IE
selText = document.selection.createRange().text;
} else () { // Standards-based browsers
selText = document.getSelection();
}
// This simple example does not include legacy browsers like Netscape 4, etc.
if (selText !== "") {
return true
}
return false;
}
您可以更改它以返回选择并以其他方式对其进行操作。但是这里返回的布尔值可以确定您的按钮是否出现。
IE使用attachEvent ,Firefox 使用addEventListener等。al,并监听 mouseup 事件。