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/
(同样输出看起来很糟糕,因为它不会被调整为那么小)
答案 0 :(得分:0)
我认为你的问题出在grabCalculator函数中。 尝试更改:
diffx = parseInt(calculator.style.left) – mousex;
diffy = parseInt(calculator.style.top) – mousey;
要:
diffx = parseInt(calculator.offsetLeft) – mousex;
diffy = parseInt(calculator.offsetTop) – mousey;
也把它放在主:
addEvent(..., grabCalculator, ...);
答案 1 :(得分:0)
在main中,设置初始计算器坐标如下:
calculator.style.top = 0 + "px";
calculator.style.left = 0 + "px";
根本不要使用getStyle。之后直接访问它。它会起作用,因为你将这两行放入主页。