JavaScript:检查两个div之间的冲突

2022-05-26 00:00:00 collision javascript overlapping

有没有办法检查名为"Character"的DIV是否与名为"GROUND"的DIV重叠?

我想用干净的Java脚本来做这件事,我知道jQuery更好,但那不是我想要的。 我看到这个帖子:check collision between certain divs?,但它没有返回任何东西。

感谢您的帮助。


解决方案

首先,我建议您查看HTML5canvas元素,根据它的声音,您想要做一个游戏,canvas非常适合;)

但是,为了回答您的问题,您可以分别使用document.createElement()getElementById()创建或获取div元素,并通过获取它们的js设置值(element.style)或使用getComputedStyle来获取它们的样式属性。

请确保,无论您如何获得这些CSS属性,都需要将它们解析为JS可以消化的内容。对于基于整数的位置,parseInt()通常有效。

下一步,你来算一算。在本例中,您需要查看角色div的顶部加上其高度是否大于地面的顶部位置。如果是,则它已发生冲突。

若要将样式设置回div,只需设置Style属性。

这里有一个例子(复制自this fiddle):

数据-lang="js"数据-隐藏="真"数据-控制台="真"数据-巴贝尔="假">
var character = document.getElementById("character");
var ground    = document.getElementById("ground");

//We could use getComputedStyle to get the style props,
//but I'm lazy
character.style.top = "10px";
character.style.height = "40px";
ground.style.top = "250px";

//For every 33ms (about 30fps)
setInterval(function(){
    
    //Get the height and position of the player
    var charTop    = parseInt(character.style.top),
        charHeight = parseInt(character.style.height);
    
    //and the top of the ground
    var groundTop = parseInt(ground.style.top);
    
    //linear gravity? Why now?
    charTop += 5;
    
    //If the character's bottom is hitting the ground,
    //Stop moving
    if(charTop + charHeight > groundTop) {
        charTop = groundTop - charHeight;    
    }
    
    //Set the character's final position    
    character.style.top = charTop + "px";
},33);
#character {
    position: absolute;
    width: 40px;
    height: 40px;
    left: 50px;
    background-color: #F00;
}

#ground {
    position: absolute;
    width: 300px;
    height: 60px;
    left: 0px;
    background-color: #A66;
}
<div id="character"></div>
<div id="ground"></div>

还有一件事:虽然当元素使用不同的定位属性(例如:球员使用top/left坐标,其中地面使用bottom)时,获取元素位置的方法很复杂,但管理起来要困难得多。

相关文章