div拖拽時取消文字選中默認事件的解決方法

當我們對div進行拖 拽時,會發現把div裏的文字也選中了,其實我並不想選中文字 ,怎麼解決呢?

我們分兩種情況說,一種情況是直接給對象加事件如obj.onmousedown; 另外一種是爲對象綁定事件addEventListener。

先說第一種:比較簡單,高版本的瀏覽直接加return false來阻止默認事件,低版本的IE系列則用obj.capature&&obj.capature();

第二,在事件綁定以後,return false 不起作用了。這時我們需要使用oEvent.preventDefault()來解決。低版本IE還是一樣。

順便提一句:事件綁定attachEvent中,不能使用this

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<style>
#div{ position:absolute; width:200px; height:200px; background:#ccc; color:#000}
</style>
<script>
ready(function(){
	var oDiv=document.getElementById('div');
	drag(oDiv);	
})

//拖拽原理:改變obj的top值與left值
function drag(obj)
{
	addEvent(obj,'mousedown',function(ev){
		var oEvent=ev||event;
		//不變的參考距離=mousedown時鼠標座標-obj到頁面的左邊距
		var disX=oEvent.clientX-obj.offsetLeft;
		var disY=oEvent.clientY-obj.offsetTop;
		addEvent(document,'mousemove',move);
		addEvent(document,'mouseup',up);
		oEvent.preventDefault();//阻止默認事件,取消文字選中
		function move(ev)
		{
        	var oEvent=ev||event;
			var left=oEvent.clientX-disX;
			var top=oEvent.clientY-disY;
			obj.style.left=left+'px';
			obj.style.top=top+'px';
			obj.setCapture&&obj.setCapture();//低版本IE阻止默認事件,取消文字選中
		}
		function up()
		{
			removeEvent(document,'mousemove',move);
			removeEvent(document,'mouseup',up);
			obj.releaseCapture&&obj.releaseCapture();//低版本IE取消阻止默認事件
		}
	})
}
//添加事件綁定
function addEvent(obj,sEv,fn)
{
	if(obj.addEventListener)
	{
		obj.addEventListener(sEv,fn,false);
	}else{
		obj.attachEvent('on'+sEv,fn);
	}
}

//刪除事件綁定
function removeEvent(obj,sEv,fnName)
{
	if(obj.removeEventListener)
	{
		obj.removeEventListener(sEv,fnName,false);
	}else{
		obj.detachEvent('on'+sEv,fnName);
	}
}
//代碼加載完執行js
function ready(fn)
{
	if(document.addEventListener)
	{
		document.addEventListener('DOMContentLoaded',fn,false)
	}else{
		document.attachEvent('onreadystatechange',function(){
			if(document.readyState=='complete')
			{fn();}
		})
	}
}	
</script>
</head>

<body>
<div id="div">選不中我哦,選不中我的。</div>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章