繁体   English   中英

我如何从 Div Top 获取并添加到这个 div top + 25?

[英]How i can Get from Div Top and add to this div top + 25?

我试图添加这个 Div 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){


        }

这也不起作用

测试文件

#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>

获取元素 offsetTop,更新它并将更新的值设置为您想要的任何元素。 请记住在更新时附加“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'

无论当前顶部是什么,这都将是 25px,这应该可以达到您想要的效果。

function addTop(element, px){
    element.style.top = (Number(element.style.top.replace(/\D/g, "")) + px) + "px";
}
addTop(document.getElementById("GAME_CHARACTER"), 25);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM