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(); 
原文地址:https://www.cnblogs.com/dakini/p/7345864.html