检测两个div冲突的最有效方法 [英] Most efficient way to detect collision of two divs

查看:197
本文介绍了检测两个div冲突的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jquery碰撞来检测两个相互重叠的对象.这是问题的 JSFiddle . (对于在HTML中包含jquery collision脚本的道歉,找不到其他方式)

I'm using Jquery Collision to detect two objects overlapping each other. Here is a JSFiddle of the problem. (apologies for including jquery collision script in HTML, couldn't find other way)

点击灰色容器中的任意位置,将绿色div移到白色div上.

Click anywhere in the gray container to move the green div over the white div.

HTML结构:

<div class="container">
    <div class="test"></div>
    <div class="menu"></div>
</div>

JS:

$(document).ready(function () {
    var hit_list;
    $(".container").click(function () {

        $(".menu").stop().animate({
            left: "+=100px"
        }, 300, function () {
            $(".menu").animate({
                left: "0"
            }, 800);
        });
        //Test for collision
        hit_list = $(".menu").collision(".test");
        if (hit_list.length != 0) {
            alert("welcome Earthling!");
        }
    });
});

我的方法的问题在于,它不会每次都检测到冲突.即使它超过了白色分割精度,也不会每次显示alert.

The problem with my method is that, it doesn't detect collision every time. Even though it passes over the white division fine, the alert isn't displayed everytime.

在检查碰撞时我在哪里出错?是否有更好/更有效的方法来检测animation期间的冲突?

Am I going wrong anywhere in checking for collision? Is there a better/more efficient method to detect collisions during animation ?

推荐答案

jQuery animate具有步骤回调( https: //api.jquery.com/animate/),它会在动画的每个步骤之后执行.

jQuery animate has a step callback (https://api.jquery.com/animate/), it gets executed after each step of the animation.

像这样使用它:

$(document).ready(function () {
    var hit_list;
    $(".container").click(function () {

        $(".menu").stop().animate({
            left: "+=100px"
        }, {
           duration: 300,
           complete: function () {
               $(".menu").animate({
                   left: "0"
               }, 800);
           },
           step: function(){
               //Test for collision
               hit_list = $(".menu").collision(".test");
               if (hit_list.length != 0) {
                   alert("welcome Earthling!");
               }
           }
         });
     });
 });

这篇关于检测两个div冲突的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆