1. 程式人生 > 實用技巧 >文字框指令碼_取得選擇的文字_跨瀏覽器_P421

文字框指令碼_取得選擇的文字_跨瀏覽器_P421

<!DOCTYPE html>
<html>
<head>
    <title>文字框指令碼_取得選擇的文字</title>
    <script type="text/javascript" src="EventUtil.js"></script>
</head>
<body>
    <p>Select some text in the textbox.</p>
    <form method="post" action="javascript:alert('Form submitted!')" id="myForm">        
        <div>
            <label for
="comments">Type something:</label><br> <input type="text" id="txtStuff" name="stuff" value="Default value"> </div> <input type="submit" value="Submit Form" id="submit-btn"> </form> <script type="text/javascript"> (
function(){ function getSelectedText(textbox){ if (typeof textbox.selectionStart == "number"){ return textbox.value.substring(textbox.selectionStart, textbox.selectionEnd); } else if
(document.selection){ return document.selection.createRange().text; } } EventUtil.addHandler(window, "load", function(event){ var textbox = document.forms[0].elements[0]; EventUtil.addHandler(textbox, "select", function(event){ console.log(getSelectedText(textbox)); }); textbox.focus(); }); })(); </script> </body> </html>