这是我有 4 个盒子和一个圆圈(只是一些示例元素)的东西,圆圈是绝对位置,可以通过触发器自由移动 throw 箱子。
现在我需要做一些关于将圆圈输入框中的事情。我想知道是否有任何方法可以定义自定义事件处理程序,例如“circleenter”而不是“mouseenter”
这是一个JSFiddle
当鼠标悬停在每个框上时,圆圈将移动到该框并更改颜色假设我们也想更改所有通过的方 block 的颜色或在路径中的方 block 上做其他事情。
脚本:
$(document).ready(function(){
var circle=$(".circle");
$(".box").mouseenter(function(){
var $this=$(this),
idx=$this.index();
width=$this.width();
var animate={left:width*idx+18};
circle.animate(animate,200,function(){
$this.css("background","#888");
});
});
});
CSS:
#box-wrapper{
position:relative;
width:400px;
height:100px;
}
.box{
width:75px;
height:75px;
border:1px solid #000;
background:#ccc;
float:left;
cursor:pointer;
}
.circle{
position:absolute;
width:36px;
height:36px;
border-radius:50%;
background:#fff800;
left:18px;
top:18px;
}
这只是一个例子所以问题是在这种情况下我们可以有类似$(".box").on("circleenter")
的东西吗?
提前致谢。
最佳答案
您不能让事件自动触发,但您可以使用记录在案的 jQuery 触发方法触发自定义事件 here .文档中的示例:
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
从评论来看,您似乎希望在圆圈穿过正方形时触发事件,而不管鼠标是否已进入圆圈。在这种情况下,除了在动画上使用“进度”选项外,我看不到任何解决方案,并检查您是否在每一步都输入了一个正方形。不过,您需要注意性能问题...
$(document).ready(function(){
var circle=$(".circle");
$('.box').on('circleenter', function(){
$this.css("background","#888");
});
$(".box").mouseenter(function(){
var $this=$(this),
idx=$this.index();
width=$this.width();
var animate={left:width*idx+18};
var lastBoxId = null;
circle.animate(animate,
{duration: 200,
progress: function(){
//Check whether the circle has entered a box
var currentBox = //Get the current box;
if(currentBox && currentBox.id != lastBoxId){
$(currentBox).trigger('circleenter');
lastBoxId = currentBox.id;
}
}});
});
});
这里有一些 SO 答案可能有助于找到元素之间的重叠:
jQuery/JavaScript collision detection
How to detect overlapping HTML elements
但是如果没有帮助的话,谷歌搜索会出现更多。
关于javascript - 元素输入上的 JQuery 自定义事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19516420/