我在div标签
中设置了一个简单的按钮<div align="right">
<button onclick='act(this, "Goals")'>Goals</button>
<button onclick='act(this, "Achievements")'>Achievements</button>
<button onclick='act(this, "Peoples")'>Peoples</button>
</div>
<div id="test" style="height: 10px; background: blue"></div>
我需要将#test div的宽度设置为按下按钮的左侧位置。 这是我在函数函数中的js代码:
var test = document.getElementById('test');
test.style.width = sender.offsetLeft + "px";
问题是#test总是出错宽度值。似乎sender.offsetLeft不是我所期望的那样。如何获得精确按钮的左侧位置?
答案 0 :(得分:1)
var result=document.getElementById('result');
var buttons=document.getElementsByTagName('button');
function act(sender,extras){
result.innerHTML="";
var test = document.getElementById('test');
test.style.left=sender.offsetLeft + "px";
for (var i=0;i<buttons.length;i++){
result.innerHTML+="Button "+(i+1)+" offset : "+buttons[i].offsetLeft+"<br>";
}
result.innerHTML+="Sender offset :"+sender.offsetLeft;
}
&#13;
#test{position:absolute;}
&#13;
<div align="right">
<button onclick='act(this, "Goals")'>Goals</button>
<button onclick='act(this, "Achievements")'>Achievements</button>
<button onclick='act(this, "Peoples")'>Peoples</button>
</div>
<div id="test" style="height: 50px;width:50px; background: blue"></div>
<div id="result"></div>
&#13;