天天看點

js禁止選中圖檔和文字

在寫一個圖檔檢視的插件時,需要禁止選中圖檔和文字,方法如下:

if(document.all){
        document.onselectstart= function(){return false;}; //for ie
   }else{
        document.οnmοusedοwn= function(){return false;};
        document.οnmοuseup= function(){return true;};
  }
  document.onselectstart = new Function('event.returnValue=false;');
           

但是這種方法在執行完後 會影影響頁面的其他元素,比如input不能擷取焦點,更好的寫法是:

ie:document.selection.empty() 

ff:window.getSelection().removeAllRanges() 

相容性的寫法(不僅不影響選中效果,而且能清楚對其他元素影響):

window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); 
           

轉載于:https://www.cnblogs.com/dakini/p/7345864.html