用鼠标拖动图片

function dragPic(e){
var e = e || window.event;
var myElement = e.srcElement || e.target;
if(e.preventDefault)
e.preventDefault(); //避免事件默认处理
else 
return false;
var myPic = document.getElementById("myPic");
myPic['draging'] = true; //设置拖动属性为true
var relLeft = e.clientX - parseInt(myElement.style.left);
var relTop = e.clientY - parseInt(myElement.style.top);
//当鼠标放开时,则停止拖动
myElement.onmouseup = function(){
myPic['draging'] = false;
}
// 定义鼠标的移动事件,注意这里是document
// 表示图片的整个网页里的鼠标移动
document.onmouseover = function(eMove){
// 获取真实的时间变量
var eMove = eMove || window.event;
if(myPic['draging'] == true){
// 设置新的left属性,减去鼠标点距左上角的距离
myElement.style.left = eMove.clientX - relLeft + "px";
myElement.style.top = eMove.clientY - relTop + "px";
return false;
}
}
}
// 当网页加载好以后就为图片拖动定义事件
window.onload = function(){
var myPic = document.getElementById("myPic");
// 定义一个属性用于存储是否正在拖动
myPic['draging'] = false;
// 根据浏览器的不同,调用不同的添加事件监听器
if(navigator.userAgent.indexOf("MISE")>0){ //ie
//为图片定义鼠标按下事件
myPic.attachEvent("onmousedown", dragPic);
}
else{ //非IE
myPic.addEventListener("mousedown", dragPic, false);
}

你可能感兴趣的:(javaScript)