通过使用CSS3变换检测元素if通过另一个元素 [英] Detect element if over another element via using CSS3 Transform
问题描述
如果元素超过另一个元素,任何简单的方法检测元素?
Any easy way to detect element if its over another element ?
我使用CSS3 transform移动元素。 (因为 )
I'm using CSS3 transform to move a element. (because)
示例:
- 所有元素大小为10x10像素
Example : - All element size 10x10 pixels
- 元素#A
transform:translate(170px,180px)
< - 此元素可以控制移动 - 元素# c $ c> transform:translate(200px,200px)
- Element#A
transform : translate(170px, 180px)
<-- This element can controll for moving - Element#B
transform : translate(200px, 200px)
一些元素?
我使用jQuery元素控制器的完整演示: 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
推荐答案
使用 offset
获得移动对象的位置
,并将其与块进行比较。
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.
此外,您使用 setInterval
创建了一个开销。我把它移动到 keyup
事件处理程序。
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.
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');
}
});
这篇关于通过使用CSS3变换检测元素if通过另一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!