Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

jquery - Detect element if over another element via using CSS3 Transform

Any easy way to detect element if its over another element ?

I'm using CSS3 transform to move a element. (because)

Example : - All element size 10x10 pixels

  • Element#A transform : translate(170px, 180px) <-- This element can controll for moving
  • Element#B transform : translate(200px, 200px)

How to detect is element#A over some element ?

My full demo with jQuery element controller : http://jsfiddle.net/ndZj5/

var over = false;
// do something with `over` to `true` to detect this...
if(!over) {
  my.css('transform','translate('+x+'px,'+y+'px)');
}

Take a tour on my demo , press keyboard arrows to controll

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');
    }

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...