每次与其他元素碰撞时调用函数

时间:2015-08-27 13:59:11

标签: javascript collision getelementsbyclassname

.cpp

bx1是固定的。通过滚动页面,bx1应该在每次移动bx2时更改颜色。

JSFiddle

还试过这个:

var bx1 = $(".bx1");
var bx2 = $(".bx2");

setInterval(function(){
    if (collision(bx1,bx2)==true) (bx1).css("background","red");
    else (bx1).css("background","blue");
},0);

如何在特定类的每个元素上执行此功能?

2 个答案:

答案 0 :(得分:0)

我认为,因为你想检查你需要循环的每个.bx2的碰撞并检查碰撞。

var bx1 = $(".bx1");
var bx2 = $(".bx2");

setInterval(function () {
    if (collision(bx1, bx2) == true)(bx1).css("background", "red");
    else(bx1).css("background", "blue");
}, 0);


function collision($div1, $divs) {
    for (i = 0; i < $divs.size(); i++) {
        if (isColliding($div1, $divs.eq(i))) {
            return true
        }
    }
    return false;
};

function isColliding($div1, $div2) {
    var x1 = $div1.offset().left;
    var y1 = $div1.offset().top;
    var h1 = $div1.outerHeight(true);
    var w1 = $div1.outerWidth(true);
    var b1 = y1 + h1;
    var r1 = x1 + w1;
    var x2 = $div2.offset().left;
    var y2 = $div2.offset().top;
    var h2 = $div2.outerHeight(true);
    var w2 = $div2.outerWidth(true);
    var b2 = y2 + h2;
    var r2 = x2 + w2;

    if (b1 > y2 && r1 > x2 && y1 < b2 && x1 < r2) return true;
    else return false;
}

Updated Fiddle

答案 1 :(得分:0)

since you have 3 div with the same class name, so you need to do for loop in your collision for each bx2 class

i have updated you fiddle please have a look at

 <http://jsfiddle.net/c7Lq1ns9/4/>

hope this will solve your problem

please mark this as answer if this helps you

thanks