2012-01-28 37 views
2

我使用的是被稱爲disableSelection防止對特定元素的文本選擇的JavaScript函數。這個函數的聲明是在這裏:對面disableSelection功能,用於啓用文本選擇特定的HTML元素

function disableSelection(target) 
{ 
    if (typeof target.onselectstart!="undefined") //IE route 
     target.onselectstart=function(){return false} 
    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route 
     target.style.MozUserSelect="none" 
    else //All other route (ie: Opera) 
     target.onmousedown=function(){return false} 
    target.style.cursor = "default" 
} 

我想整個頁面上禁用文本選擇不同的表單元素。如果我調用disableSelection(document.body),它會完成這項工作,但它也會禁用表單元素上的文本選擇(但這隻發生在Firefox上)。

我的問題是我怎麼能防止表單字段受着這個文本的禁用腳本?我可以標記除表單字段以外的所有內容,但它需要付出很多努力。

我會很感激任何幫助。

注:我發現disableSelection腳本here

回答

0

通過從事件返回false,將禁用瀏覽器(選擇文本)的默認行爲。我會爲此修改這個功能;

function disableSelection(target, enable) 
{ 
    if (typeof target.onselectstart!="undefined") //IE route 
     target.onselectstart=function(){return enable} 
    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route 
     target.style.MozUserSelect=enable?"all":"none"; 
    else //All other route (ie: Opera) 
     target.onmousedown=function(){return enable} 
    target.style.cursor = "default" 
} 

然後打電話給你的東西;

disableSelection(document.body, false); 
disableSelection(document.forms[0], true); 

應該工作(沒有測試)

+0

它沒有工作,但我會嘗試更多。如果我成功了,我會在這裏發帖。 – Amiga500 2012-01-31 18:45:55

+0

爲了測試它是否有效,我調用了disableSelection(document.body,false);我稱之爲disableSelection(document.body,true);緊隨其後。但是整個頁面沒有啓用選擇。任何想法? – Amiga500 2012-01-31 18:48:11

+0

哪個瀏覽器和版本? – japrescott 2012-01-31 21:36:28

0

腳本必須下<body>標籤。如果u想DIV只禁用:disableSelection(document.getElementById('divName'))

0

這個工作對我來說,只是在鍍鉻測試:

function enableSelection(target) { 
    //For IE This code will work 
    if(typeof target.onselectstart != "undefined") { 
     target.onselectstart = function() { 
      return true; 
     } 
    } 

    //For Firefox This code will work 
    else if(typeof target.style.MozUserSelect != "undefined") { 
     target.style.MozUserSelect = "all"; 
    } 

    //All other (ie: Opera) This code will work 
    else { 
     target.onmousedown = function() { 
      return true; 
     } 
     target.style.cursor = "default"; 
    } 
}