国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JavaScript 選中文字并響應獲取的實現代碼

2019-11-20 23:42:15
字體:
來源:轉載
供稿:網友
本人不怎么會寫JS,但是會搜索,這里找到了些別人寫好的東西:
復制代碼 代碼如下:

select(document, tanchu);
/*=select[[
*
* 跨瀏覽器選中文字事件
* @param
* object o 響應選中事件的DOM對象,required
* function fn(sText,target,mouseP)選中文字非空時的回調函數,required
* |-@param
* |-sText 選中的文字內容
* |-target 觸發mouseup事件的元素
* |-mouseP 觸發mouseup事件時鼠標坐標
*/
function select(o, fn){
o.onmouseup = function(e){
var event = window.event || e;
var target = event.srcElement ? event.srcElement : event.target;
if (/input|textarea/i.test(target.tagName) && /firefox/i.test(navigator.userAgent)) {
//Firefox在文本框內選擇文字
var staIndex=target.selectionStart;
var endIndex=target.selectionEnd;
if(staIndex!=endIndex){
var sText=target.value.substring(staIndex,endIndex);
fn(sText,target);
}
}
else{
//獲取選中文字
var sText = document.selection == undefined ? document.getSelection().toString():document.selection.createRange().text;
if (sText != "") {
//將參數傳入回調函數fn
fn(sText, target);
}
}
}
}
/*]]select=*/
function tanchu(txt,tar){
alert("文字屬于"+tar.tagName+"元素,選中內容為:"+txt);
}

 原作者見:http://momomolice.com/wordpress/archives/420.html


附:只獲得選取的文字的代碼(不響應該事件)
復制代碼 代碼如下:

function getSelectedText()
{
if (window.getSelection)
{ // This technique is the most likely to be standardized.
// getSelection() returns a Selection object, which we do not document.
return window.getSelection().toString();
}
else if (document.getSelection)
{
// This is an older, simpler technique that returns a string
return document.getSelection();
}
else if (document.selection)
{
// This is the IE-specific technique.
// We do not document the IE selection property or TextRange objects.
return document.selection.createRange().text;
}
}

函數運行后會將選取的文字返回出來。  

原作者已不可考。。。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 肥西县| 溆浦县| 台中县| 长白| 滕州市| 常山县| 惠水县| 香港 | 旬阳县| 杂多县| 商南县| 祁连县| 泸西县| 肇东市| 雅江县| 兴安盟| 梁山县| 岑巩县| 连南| 堆龙德庆县| 禄丰县| 梁平县| 诸暨市| 嘉定区| 巴中市| 章丘市| 龙南县| 江华| 丰城市| 盖州市| 洛南县| 临江市| 谢通门县| 永清县| 安仁县| 墨竹工卡县| 鹰潭市| 开封市| 罗江县| 华宁县| 凯里市|