为什么我不能读取object.style.left和object.style.top的值?
我正在尝试动态移动一个按钮。
我可以使用javascript通过执行以下操作来重置style.left和style.top的值:
document.getElementById(theButton_ID).style.left = "128px";
document.getElementById(theButton_ID).style.top = "64px";但我的问题是,我需要动态地重置‘style.left’和‘style.top’的值,使用一个比例因子,这个比例因子需要在网页加载时动态确定。
对于我的新手来说,这意味着我需要:
·获取style.left和style.top值
·将它们乘以比例因子
·将这些修改后的值分配给style.left和style.top值。
问题是我不能在第一个地方得到style.left和style.top的值,所以我不能修改它们,更不用说写回它们了。
所以很明显,我都做错了什么&我没有理解一些我应该理解的东西。
那么我到底做错了什么呢?
我错过了什么?
最重要的是,如何获得style.left & style.top的值,以便使用它们动态修改按钮的位置?
感谢大家的帮助和建议。
下面是实际的HTML / CSS/ Javascript代码…
<html>
<head>
<title>Button Dynamic Move Test</title>
<style type="text/css">
#MoveButton
{
position : absolute;
left : 8px;
top : 16px;
}
</style>
<script>
// var X_Index_Move_Factor = 1.25;
// var Y_Index_Move_Factor = 1.50;
function Move_A_Button (theButton_ID)
{
alert ( "We're in 'Move_A_Button'"
+ "\n"
+ " The Button Id = "
+ theButton_ID
);
var the_Old_Button_X_Offset = document.getElementById(theButtonId).style.left;
var the_Old_Button_Y_Offset = document.getElementById(theButtonId).style.top;
alert ( "the_Old_Button_X_Offset = "
+ "\n"
+ the_Old_Button_X_Offset
+ "the_Old_Button_Y_Offset = "
+ "\n"
+ the_Old_Button_Y_Offset
);
}
</script>
</head>
<body>
<button type = "button"
id = "MoveButton"
onclick = "Move_A_Button ('MoveButton')">
About Us
</button>
</body>
</html>发布于 2013-05-08 11:03:18
实际上,如果您不需要支持IE6或IE7 (或大约17个版本之前的FireFox ),那么获取内部数据的最佳方法如下所示:
// inside of your function:
var el = document.getElementById(button_id),
dimensions = el.getBoundingClientRect();
console.log("old x: " + dimensions.left, "old y: " + dimensions.top);
console.log("new x: " + dimensions.left * scale_X, "new y: " + dimensions.top * scale_Y);只需记住,当您设置它们时,您还必须添加度量:
el.style.top = (dimensions.top * scale_Y) + "px";
el.style.left = (dimensions.left * scale_X) + "px";使用getBoundingClient函数会给出数字形式的测量值,但.style.top / .style.left会给出字符串形式的测量值("112px"),您必须从中提取数字,然后进行修改,然后在添加回来时,将测量类型添加回......hooray
发布于 2013-05-08 10:47:05
theButton_ID是参数的名称
function Move_A_Button (theButton_ID)
{当你试图获得你所写的风格时
document.getElementById(theButtonId).style.left;你忘了加下划线
发布于 2013-05-08 10:52:46
即使纠正了拼写错误,元素最初也没有top或left样式,因为元素本身没有设置任何样式。
作为起点,element.offsetLeft和element.offsetTop是您最好的选择。
https://stackoverflow.com/questions/16431831
复制相似问题