点击需要拖动元素时,获取该元素的初始位置。
鼠标移动期间 获取元素当前的位置信息
计算
进行事件监听
拖拽的实现原理:通过事件mousedown(事件的触发) →mousemove(事件的控制) →mouseup(事件的清除),拖拽的过程就是mousemove阶段;
问题产生的原因:因为mousemove 的间隔性触发,当两次mousemove事件触发的间隔中,鼠标移动距离出了element的范围,就会产生鼠标脱离element范围,拖拽就停止,
解决方法: 将mousemove事件挂在docment,而不是对应的element,此时鼠标滑动只要不出docment范围就不会触发上述情况。
拖动事件完成的动作时是:mousedown(事件的触发) →mousemove(事件的控制) →mouseup(事件的清除) 但是mouseup的时候 同时会触发 点击事件(如果元素上面有点击事件的话)
处理办法:记录mousedown(记录开始时间) →mousemove→mouseup(记录结束时间) 的时间 根据时间长短判断是进行了点击事件还是进行了拖拽事件。
正常需求的话 就希望拖拽元素只在屏幕的可视范围内进行拖拽,不能跑出去。
在onmousemove 中添加边缘控制就好,具体范围可以根据具体需求更改。
你的obj.style.left是获取不到的因为该div没有设置style属性所以只要将样式改为行内就行了<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文哥讨厌IE</title>
</head>
<body>
<div id="over" onmousedown="down(this,event)" style="width:100pxheight:30pxbackground:redposition:absoluteleft:20pxtop:500px" onmousemove="move(this,event)" onmouseup="seup(this,event)">
</div>
<script type="text/javascript">
var posX,posY
var downX,downY
var mark=false
function down(obj,event)
{
obj.style.cursor="move"
posX=obj.style.left
posY=obj.style.top
downX=event.clientX
downY=event.clientY
mark=true
///alert(posX)
///alert(posY)
}
function move(obj,event)
{
var moveX=event.clientX
var moveY=event.clientY
if (mark) {
obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX) + "px"
obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px"
}
}
function seup(obj,event)
{
if (mark) {
var moveX=event.clientX
var moveY=event.clientY
obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX)+ "px"
obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px"
downX=moveX
downY=moveY
}
obj.style.cursor="default"
mark = false
}
</script>
</body>
</html>
能,参考下面的代码:windowAddMouseWheel()
function windowAddMouseWheel() {
var scrollFunc = function (e) {
e = e || window.event
if (e.wheelDelta) { //判断浏览器IE,谷歌滑轮事件
if (e.wheelDelta >0) { //当滑轮向上滚动时
alert("滑轮向上滚动")
}
if (e.wheelDelta <0) { //当滑轮向下滚动时
alert("滑轮向下滚动")
}
} else if (e.detail) { //Firefox滑轮事件
if (e.detail>0) { //当滑轮向上滚动时
alert("滑轮向上滚动")
}
if (e.detail<0) { //当滑轮向下滚动时
alert("滑轮向下滚动")
}
}
}
//给页面绑定滑轮滚动事件
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false)
}
//滚动滑轮触发scrollFunc方法
window.onmousewheel = document.onmousewheel = scrollFunc
}