为什么要使用监听函数?不可以直接在window.onload下使用mainDiv.onmousedown=function(){}这样的格式?我用这样的方法无法拖动,求大神帮助
主要HTML代码:<body>
<div id=box>
<img src="images/psb.jpg" alt="师大光影" id="img1"/>
<img src="images/psb.jpg" alt="师大光影" id="img2"/>
<div id=main>
<div id="left-up" class="minDiv left-up"></div>
<div id="upDiv" class="minDiv up"></div>
<div id="right-up" class="minDiv right-up"></div>
<div id="leftDiv" class="minDiv left"></div>
<div id= rightDiv class="minDiv right"></div>
<div id="left-bottom" class="minDiv left-bottom"></div>
<div id="downDiv" class="minDiv bottom"></div>
<div id="right-bottom" class="minDiv right-bottom"></div>
</div>
</div>
<div id="preview"><img src="images/psb.jpg" alt="师大光影" id="img3"/></div>
</body>
//图框拖动事件,使用以下代码无法移动
var mouseOffsetX=0;
var mouse0ffsetY=0;
var moveX=0;
var moveY=0;
mainDiv.onmousedown=function(){
odrag=true;
}
document.onmousemove=function(e){
var e=e||window.event;
var mouseX=e.clientX;
var mouseY=e.clientY;
mouseOffsetX=mouseX-mainDiv.offsetLeft;
mouseOffsetY=mouseY-mainDiv.offsetTop;
moveX=mouseX-mouseOffsetX;
moveY=mouseY-mouseOffsetY;
if(odrag==true){
mainDiv.style.left= moveX+"px";
mainDiv.style.top= moveY+"px";
}
}
document.onmouseup=function(){
odrag=false;
}
//以下为正确版
mainDiv.addEventListener("mousedown",function(e){
var e=e||window.event;
mouse0ffsetX=e.clientX-mainDiv.offsetLeft;
mouseOffsetY=e.clientY-mainDiv.offsetTop;
odrag=true;
})
document.onmousemove=function(e){
var mouseX=e.clientX;
var mouseY=e.clientY;
var moveX=0;
var moveY=0;;
moveX=mouseX-mouse0ffsetX;
moveY=mouseY-mouseOffsetY;
if(odrag==true){
mainDiv.style.left= moveX+"px";
mainDiv.style.top= moveY+"px";
math.min(Max,math.Max(0,mouseX));
}
}
document.onmouseup=function(){
odrag=false;
}
}