舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function init() { function onMouseUp() { var s1 = document.getElementById( "show1" ); var s2 = document.getElementById( "show2" ); var wTA = document.activeElement; var selection = wTA.value.substring(wTA.selectionStart, wTA.selectionEnd); s1.innerHTML = wTA.id; s2.innerHTML = selection; } document.getElementById( "demo1" ).addEventListener( "mouseup" , onMouseUp, false ); document.getElementById( "demo2" ).addEventListener( "mouseup" , onMouseUp, false ); } /* 《程式語言教學誌》的範例程式 檔名:document001.js 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2011 年 8 月 */ |
第 5 行的變數 (variable) wTA 藉由 document 的 activeElement 屬性取得目前聚焦的元素物件 (object)
5 | var wTA = document.activeElement; |
這個例子會使 id 屬性 (attribute) 為 demo1 的元素顯示所聚焦的 id 號碼, id 屬性為 demo2 的元素顯示所選取的文字字串。也就是說,如果有兩個 <textarea> 元素, id 分別為 demo1 與 demo2 ,使用滑鼠選擇其中一個 <textarea> 之時,該 <textarea> 就是目前聚焦的元素。
我們以下面的 HTML 文件載入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!DOCTYPE html> < html > < head > < title >HTML DOM DEMO</ title > < script src = "document001.js" type = "text/javascript" ></ script > </ head > < body onload = "init();" > < textarea id = "demo1" rows = "2" cols = "30" >There is no spoon.</ textarea > < textarea id = "demo2" rows = "2" cols = "30" >Choice. The problem is choice.</ textarea > < br / > Active Element Id: < span id = "show1" ></ span >< br / > Selected Text: < span id = "show2" ></ span > </ body > </ html > <!-- 《程式語言教學誌》的範例程式 檔名:document001.html 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2011 年 8 月 --> |
瀏覽器 (broswer) 開啟,選取其中 "spoon" 文字,結果如下

中英文術語對照 | |
---|---|
元素 | element |
變數 | variable |
物件 | object |
屬性 | attribute |
瀏覽器 | broswer |
您可以繼續參考
基本概念
文件物件 document
- 屬性
- document.activeElement
- document.alinkColor
- document.anchors
- document.bgColor
- document.cookie
- document.documentElement
- document.documentURI
- document.forms
- document.images
- document.inputEncoding
- document.lastModified
- document.lastStyleSheetSet
- document.linkColor
- document.links
- document.location
- document.plugins
- document.preferredStyleSheetSet
- document.readyState
- document.referrer
- document.selectedStyleSheetSet
- document.styleSheets
- document.styleSheetSets
- document.title
- document.URL
- document.vlinkColor
- 方法
- document.close()
- document.createAttribute(name_str)
- document.createElement(element_str)
- document.createTextNode(text_str)
- document.enableStyleSheetsForSet(ss_str)
- document.getElementById(id_str)
- document.getElementsByClassName(cn_str)
- document.getElementsByName(n_str)
- document.getElementsByTagName(tn_str)
- document.hasFocus()
- document.open()
- document.write(str)
- document.writeln(str)
相關目錄
HTML DOM 快速導覽
JavaScript 教材
首頁
參考資料
http://www.whatwg.org/specs/web-apps/current-work/#focus-management
https://developer.mozilla.org/en/DOM/document.activeElement
沒有留言:
張貼留言