在不同的对象上应用相同的 id 并分别对它们进行动画处理 (jQuery)

Apply same id on different objects and animate them separately (jQuery)

本文关键字:动画 jQuery 处理 对象 应用 id      更新时间:2023-09-26

假设我有一排div,如下所示:jsfiddle.net/AlphaCrack/veuc80he/1/

不想单独对它们进行动画处理,但要保持相同的 id,因为我可能不得不创建大量这样的div,而且我不想创建大量的 css id。如您所见,在多个元素上应用相同的 id 只会影响第一个元素。为什么?我该怎么做才能使用相同的 id 分别对它们进行动画处理。

该 HTML:

<div id="TEST">
</div>
<div id="TEST">
</div>
<div id="TEST">
</div>
<div id="TEST">
</div>

CSS:

#TEST
{
    width: 100px;
    height: 100px;
    background-color: #252525;
    border: 1px solid #AAFF00;
    float: left;
}

jQuery:

$("#TEST").mouseenter(function(){
    $("#TEST").stop();
    $("#TEST").animate({"height":"200px"},200);
});
$("#TEST").mouseleave(function(){
    $("#TEST").stop();
    $("#TEST").animate({"height":"100px"},200);
});

实际上,我有大量的动画帧(具有相同的id)保存数据库中的每个图像。当我将鼠标悬停在图片上时,我需要分别对每一帧进行动画处理。

首先,在单个页面中具有重复的id属性是无效的,因为它们必须是唯一的。这就是为什么只有第一个元素受到事件的影响。请改用类。

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

然后在 JS 中,您可以使用公共类停止.test元素上的所有动画,this仅引用引发事件的元素。

$(".test").mouseenter(function () {
    $(".test").stop();
    $(this).animate({ "height": "200px" }, 200);
}).mouseleave(function () {
    $(".test").stop();
    $(this).animate({ "height": "100px" }, 200);
});

更新的小提琴

您还可以简化代码以使用 hover ,这将消除对stop()的需求,这会导致在快速悬停在元素上时偶尔出现错位:

$(".test").hover(
    function() { $(this).animate({ "height": "200px" }, 200); }, 
    function() { $(this).animate({ "height": "100px" }, 200); }
);

示例小提琴

不幸的是,你不能让 DOMElements 具有相同的 ID,这不适用于 jQuery。

必须使用类。

$(".TEST").mouseenter(function(){
    $(this).animate({"height":"200px"},200);
});
$(".TEST").mouseleave(function(){
    $(this).stop();
    $(this).animate({"height":"100px"},200);
});

这是解决方案:http://jsfiddle.net/ruxhighwind/veuc80he/6/

我要做的是使用其他类型的jquery选择器,可能基于父级,就像这样:

$(".parent > div").each(function(i){
  $(this).mouseenter(function(){
    $(this).stop();
    $(this).animate({"height":"200px"},200);
  });
  $(this).mouseleave(function(){
    $(this).stop();
    $(this).animate({"height":"100px"},200);
  });
});

并将它们包装在父div 中!刚刚在您的小提琴中测试并且工作正常!但请记住,拥有多个相同值的 id 是不好的形式。