在寫一個圖片查看的插件時,需要禁止選中圖片和文字,方法如下:
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();