[英]Javascript: Check collision between two divs
是否有任何方法可以检查名称为“字符”的 DIV 是否与名称为“地面”的 DIV 重叠?
我想用干净的 Javascript 来做到这一点,我知道 jQuery 更好,但这就是我不想要的。 我看到了这篇文章: 检查某些 div 之间的碰撞? ,但它不会返回任何东西。
感谢您的帮助。
首先,我建议您查看 HTML5 canvas
元素,因为从它的声音来看,您想制作一个游戏,而canvas
非常适合;)
但是,要回答您的问题,您可以分别使用document.createElement()
或getElementById()
创建或获取 div 元素,并通过获取它们的 JS 设置值 ( element.style
) 或使用getComputedStyle 来获取它们的样式属性element.style
d 更喜欢在 CSS 中设置初始值。
请确保,无论您如何获得这些 CSS 属性,都需要将它们解析为 JS 可以消化的内容。 对于基于整数的位置, parseInt()
通常可以解决问题。
接下来,你做数学。 在这种情况下,您需要查看字符 div 的顶部加上其高度是否大于地面的顶部位置。 如果是,它已经发生碰撞。
要将样式设置回 div,您只需设置 style 属性即可。
这是一个例子(从这个小提琴复制):
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
),但管理起来要困难得多。
该链接答案中唯一使用的 jQuery 是获取 div 的width
、 height
和position
,使用纯 JS 检索这些有点微不足道:
CSS / JavaScript - 如何获得元素的渲染高度?
普通javascript中的jquery position()
因为它不返回任何东西.top
.left
和height
的变量return
的语句都依赖于该检索信息上面提到的jQuery功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.