js禁止選中圖片和文字


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

 if(document.all){
        document.onselectstart= function(){return false;}; //for ie
   }else{
        document.onmousedown= function(){return false;};
        document.onmouseup= 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(); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM