Detect element if over another element via using CSS3 Transform

扶醉桌前 提交于 2019-11-28 02:13:05

You need to use offset to get the position of the moved object and compare it with the "blocks".

I've setup in my demonstration the "blocks" to change to blue when they are overlayed. But you can do whatever you want.

Also you were creating an overhead with your setInterval. I've moved it to the keyup event handler.

Further I recommend you to store the position of the "blocks" in an array if they are static elements and access them when needed.

Working example

var objTop = my.offset().top,
    objLeft = my.offset().left,
    objWidth = my.width(),
    objHeight = my.height();            

$('.fixed').each(function(e){
    var self = $(this),
        selfLeft = self.offset().left,
        selfTop = self.offset().top,
        selfWidth = self.width(),
        selfHeight = self.height();

    self.css('background','black');                 

    if((objLeft + objWidth) > selfLeft && objLeft < (selfLeft + selfWidth) && (objTop + objHeight) > selfTop && objTop < (selfTop + selfHeight)){
        self.css('background','blue');
    }

});

You can use .offset to see the position of an element relative to the document. This does take into account translate. You can get the coordinates of the rectangle with .offset and then .offset.left + width / .offset.top + height. Then you can easily check for an overlap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!