Javascript 如何从Div-Top获取并添加到此Div-Top+;25?
我试图添加这个DivJavascript 如何从Div-Top获取并添加到此Div-Top+;25?,javascript,Javascript,我试图添加这个Divtop:+25,但我浪费了6个小时,没有更多的想法如何实现它 我试着这样做: var testDiv = document.getElementById("GAME_NPC").offsetTop; var testDiv2 = document.getElementById("GAME_CHARACTER").offsetTop += "32px"; //alert(testDiv2); if (testDiv == testDiv2) {} 但这不起作用
top:+25
,但我浪费了6个小时,没有更多的想法如何实现它
我试着这样做:
var testDiv = document.getElementById("GAME_NPC").offsetTop;
var testDiv2 = document.getElementById("GAME_CHARACTER").offsetTop += "32px";
//alert(testDiv2);
if (testDiv == testDiv2) {}
但这不起作用
var testDiv = document.getElementById("GAME_NPC").offsetTop;
var testDiv2 = document.getElementById("GAME_CHARACTER");
var top = testDiv2.offsetTop;
top += 32; //that one is int
testDiv2.style.top = top + "px"; // and that one should be string with 'px'
if(testDiv2 == testDiv){
}
这也不起作用
test.css
#GAME_CHARACTER {
display: block;
position: absolute;
width: 32px;
height: 48px;
left: 32px;
top: 32px;
z-index:200;
}
#GAME_NPC {
display: block;
position: absolute;
left: 0;
top:120px;
width: 96px;
height: 128px;
background: url(http://xxx/npc.gif) no-repeat center;
}
html代码:
<DIV id="GAME_CHARACTER" class="left-stand" style="background-image: url(http://xxx/character.png);"></DIV>
<DIV id="GAME_MAP2"><DIV id="GAME_NPC"></DIV></DIV>
抓取元素偏移,更新它并将更新值设置为所需的任何元素。请记住在更新时附加“px”
var testDiv = document.getElementById("my-div-id");
var top = testDiv.offsetTop;
top += 32; //that one is int
testDiv.style.top = top + "px"; // and that one should be string with 'px'
这将所有25像素到当前的顶部,这将达到你想要的效果
function addTop(element, px){
element.style.top = (Number(element.style.top.replace(/\D/g, "")) + px) + "px";
}
addTop(document.getElementById("GAME_CHARACTER"), 25);
Offset top是只读的,它不会移动元素,而是使用css。另外:不可能对字符串执行算术运算。是否要根据网页顶部或其父元素移动div。对于第二种情况,您可以使用
margin
或padding
,对于第一种情况,您可以使用document.documentElement.scrollTop
是top:120pox代码>问题中的输入错误,还是这是您实际程序中的复制粘贴片段?@Arfeo是的,我错了。对不起,请在帖子中添加相关的css,这可能有助于调试它,并看到参数“top”已更新。不确定您想要实现什么,我以为您正在尝试更新元素的样式“top”。但现在我如何检查testDiv==testDiv2+32px?我不需要permament+32px来检查我认为这是解决问题的错误方法。您不需要移动一个div来比较另一个div。只需执行如下操作:if(testDiv.offsetTop==testDiv2.offsetTop+32){}谢谢!,我犯了错误,因为我使用+32,但我需要-32。。。。。。。。。谢谢没问题!需要注意的一点是,将数字括在引号中意味着它是一个字符串,不再是数字。你不能指望能用字符串做传统的数学。它不会那样工作的。