Home

Written by Mary Ma, and build some interesting tools .

文本框跟随鼠标移动

2016-08-10

关于这个知识点,我原来看过三遍总觉得自己学会了,今天再用发现还得查资料,这样可不行啊!

实现效果—>查看效果

鼠标点击文本框的标题,文本框跟着鼠标移动,鼠标松开文本框不再移动。

知识点:

  • event.clientX: 事件属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的水平坐标
  • event.clientY:事件属性返回当事件被触发时鼠标指针向对于浏览器页面(客户区)的垂直坐标。
  • offsetLeft:元素的左外边框到包含元素的左内边框的像素距离。
  • offsetLeft:元素的左外边框到包含元素的左内边框的像素距离。
  • offsetTop:元素的上外边框到包含元素的上内边框的像素距离。
  • onmousedown:鼠标按键按下事件
  • onmouseup:鼠标按键弹起事件
  • onmousemove:鼠标移动事件

整体思路

(感觉一张好图胜过千言万语)

鼠标点下的时候执行 ommousedown,计算 clientX,clientY,offsetLeft,offsetTop (此时 clientX,clientY 是点击时的坐标) 求出 disX = clientX - offsetLeft,disY = clientY - offsetTop 执行 onmousemove,对弹框定位 left = clientX - disX,top = clientY - disY (此时 clientX 和 clientY 是移动后的坐标,是随时变化的)

上代码

function move() {
	var oTitle = document.getElementById("title");
	//点击时
	oTitle.onmousedown = function(event) {
		var disX = event.clientX - tip.offsetLeft;
		var disY = event.clientY - tip.offsetTop;
		//移动
		document.onmousemove = function(event) {
		tip.style.left = event.clientX + 125 - x + "px";
		tip.style.top = event.clientY + 75 - y + "px";
	}
	//弹起
	oTitle.onmouseup = function(){
		document.onmousemove = null;
	}

}

其他

在 JS 中修改关于尺寸时要加单位“px” 这样弹框可以拉到屏幕以外的位置,可以根据自己的需求更改 可以参考课程DOM 事件揭秘第四章

Home

Written by Mary Ma, and build some interesting tools .