昨天在课堂上,我的老师放了一些代码让我们在家测试,但我似乎无法让代码工作。代码应该做的是在按住鼠标的同时移动一个 div。我给我的朋友看了,我们认为问题出在:
calculator.style.top = getStyle(calculator, "top");
calculator.style.left = getStyle(calculator, "left");
function getStyle(object,styleName)
{
if (window.getComputedStyle)
{
return document.defaultView.getComputedStyle(object, null).getPropertyValue(styleName);
}
else if (object.currentStyle)
{
return object.currentStyle[styleName];
}
}
但我们似乎仍然无法让它发挥作用。帮助将不胜感激。这里还有完整的代码,以防您需要查看它:
diffx = null;
diffy = null;
off = document.getElementById("buttonOff");
on = document.getElementById("calcButton");
calculator = document.getElementById("calculator");
calculator.style.top = getStyle(calculator, "top");
calculator.style.left = getStyle(calculator, "left");
function getStyle(object,styleName)
{
if (window.getComputedStyle)
{
return document.defaultView.getComputedStyle(object, null).getPropertyValue(styleName);
}
else if (object.currentStyle)
{
return object.currentStyle[styleName];
}
}
function grabCalculator(e)
{
var evt = e || window.event;
calculator = evt.target || evt.srcElement;
var mousex = evt.clientX;
var mousey = evt.clientY;
diffx = parseInt(calculator.style.left) – mousex;
diffy = parseInt(calculator.style.top) – mousey;
addEvent(document, "mousemove", moveCalculator, false);
addEvent(document, "mouseup", dropCalculator, false);
}
function moveCalculator(e)
{
var evt = e || window.event;
var mousex = evt.clientX;
var mousey = evt.clientY;
calculator.style.left = mousex + diffx + "px";
calculator.style.top = mousey + diffy + "px";
}
function addEvent(obj, eventType, fnName, cap)
{
if (obj.attachEvent)
{
obj.attachEvent("on" + eventType, fnName);
}
else
{
obj.addEventListener(eventType, fnName, cap);
}
}
function removeEvent(obj, eventType, fnName, cap)
{
if (obj.attachEvent)
{
obj.detachEvent("off" + eventType, fnName);
}
else
{
obj.removeEventListener(eventType, fnName, cap);
}
}
function dropCalculator(e)
{
removeEvent(document,"mousemove", moveCalculator, false);
removeEvent(document, "mouseup", dropCalculator, false);
}
function main() {
alert("TEST");
//store top and left values of calculator
calculator.style.top = getStyle(calculator, "top");
calculator.style.left = getStyle(calculator, "left");
calcButtonState = true;
}
window.onload = main;
再次感谢!桑德罗
编辑:添加 Jsfiddle 链接:http: //jsfiddle.net/7225J/
(而且输出看起来很糟糕,因为它不应该被调整到那么小)