JavaScript中的Accelerator UI

我可以在客户端使用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 onm ouseUp(evt){
            if (isAcceleratorHidden()){
                var event2 = (document.all) ? window.event : evt;
                showAccelerator(event2.clientX, event2.clientY);
            }
        }

        function alertSelection(){
            alert(getSelectedText());
        }

        document.onmouseup = onm ouseUp;
    </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>
上一篇:javascript-更改element.innerHTML之后,MooTools事件侦听器消失


下一篇:Vue实例方法之事件的实现