zoukankan      html  css  js  c++  java
  • 禁止拖选文本的方法

    最近在做一个模拟的window窗口,遇到调整窗口大小时,会拖选相关元素,
    尝试了以下的方法,有点作用,但是最好的还是直接禁用document的选择,调整大小mouseup,再恢复.

    <body>
    	<div style="border:10px solid green; margin:50px; padding:50px;" id="div1">
    	<pre>禁止拖放对象文本被选择的方法: 
    	1.ie中设置拖放对象的onselectstart返回false,在ff中设置样式MozUserSelect(css:-moz-user-select)为none。 
    	这种方法只能禁止拖放对象本身被选择。 
    	2. 
    	ie:document.selection.empty() 
    	ff:window.getSelection().removeAllRanges() 
    	兼容的写法: 
    	window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); 
    	这种方法不但不影响拖放对象的选择效果,还能对整个文档进行清除. 
    	</pre>
    	</div>
    	<div style="height:100px; background:skyblue; margin:50px; padding:50px;" id="div2">
    		止拖放对象文本被选择的方法: 
    		1.ie中设置拖放对象的onselectstart返回false,在ff中设置样式MozUserSelect(css:-moz-user-select)为none。 这种方法只能禁止拖放对象本身被选择。 
    	</div>
    	<hr>
    	<input type="text" name="user" id="user" value="sdfdfdfsdfdsf" style="100%;line-height:40px; height:40px;" />
    
    	<script>
    		function $id(id){ return document.getElementById(id); }
    		var div1 = $id('div1'), div2 = $id('div2'),user = $id('user');
    		div1.onselectstart = function(){ 
    			console.log('select start'); 
    			//测试:Chrome IE
    			//1:若onselectstart是在 div1 内部发生的 则禁止选中 div1内的内容,
    			//(但chrome可以选中 div1以外的内容,ie不能)
    			//2: 若onselectstart是在 div1 外部发生,还是可以选中div1内的内容
    			return false; 
    		}
    
    		//获取当前选择 并取消选择
    		/** 清楚当前选中内容
    		* chrome firefox:
    		  s = window.getSelection(); s.empty(); 
    		  or s.removeAllRanges(); // s.collapse(1);
    		* ie:document.selection.empty()
    		* 兼容的写法: 
    		  window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); 
    			这种方法不但不影响拖放对象的选择效果,还能对整个文档进行清除.
    		*/
    		
    		/**
    		 * 禁止选中文本
    		 */
    		function disableSelection(ele){
    			if(typeof ele.onselectstart !="undefined"){//ie
    				ele.onselectstart = function(){ return false; }
    			}else if(typeof ele.style.MozUserSelect !='undefined'){
    				ele.style.MozUserSelect = 'none';
    			}else{
    				ele.onmousedown = function(){return false;}
    			}
    		}
    	</script>
    </body>
    
  • 相关阅读:
    按分类统计商品总数的性能优化思考
    Flash/Flex学习笔记(52):使用TweenLite
    Flash/Flex学习笔记(36):自己动手实现一个滑块控件(JimmySilder)
    解决JQuery中的ready函数冲突
    Flash/Flex学习笔记(41):碰撞检测
    Flash/Flex学习笔记(34):AS3中的自定义事件
    如何改变AspNetPager当前页码的默认红色?
    Flash/Flex学习笔记(42):坐标旋转
    Flash/Flex学习笔记(39):弹性运动
    C#检测SqlServer中某张表是否存在
  • 原文地址:https://www.cnblogs.com/stephenykk/p/4153199.html
Copyright © 2011-2022 走看看