jQuery - 更改单个 DIV 的 CSS

jQuery - Change CSS of a single DIV

本文关键字:DIV CSS 单个 jQuery      更新时间:2023-09-26

我有这个HTML代码:

<div id="cont">
    <div class="us"></div>
    <div class="us"></div>
    <div class="us"></div>
</div>

和这个JS代码:

$(".us").mouseenter(function() {
    $(this).animate({marginRight: "10px"}, "fast");
});

问题是这三个要素发生了变化。我在没有 cont DIV 的情况下尝试了它并且工作得很好,只更改了一个元素,但我需要它。另外,我尝试向DIV提供单个ID,但一直失败。

您可以通过

多种方式选择一个项目。

//the first one
$(".us").first().mouseenter(function() {
    $(this).animate({marginRight: "10px"}, "fast");
});
//the second one
$(".us").eq(1).mouseenter(function() {
    $(this).animate({marginRight: "10px"}, "fast");
});
//the third one
$(".us:nth-child(3)").mouseenter(function() {
    $(this).animate({marginRight: "10px"}, "fast");
});

这里的问题在于您的 CSS 代码,因为div元素就像一个块一样,您可以通过添加margin来增加所有容器,而其他元素也会占用空间。您可以添加以下内容以使每个div添加边距:

.us {
  float:right;
  clear:right;
}

您的演示 http://jsfiddle.net/6H8f4/14/

试试这个:

$(".us:first-child").mouseenter(function() {
    $(this).animate({marginRight: "10px"}, "fast");
});

$(".us:last-child").mouseenter(function() {
        $(this).animate({marginRight: "10px"}, "fast");
    });

$(".us:nth-child(index)").mouseenter(function() {
        $(this).animate({marginRight: "10px"}, "fast");
    });

做了一个小提琴

$(".us").mouseenter(function() {
    $(this).animate({'margin-right': 100}, "fast");
});
$(".us").mouseout(function() {
    $(this).animate({'margin-right': 5}, "fast");
});

http://jsfiddle.net/QjL9J/1/

使用动画时,默认情况下将整数设置为值将使它们成为PX

此外,CSS 属性应该在 Animate 对象的 '' 中,并写入实际属性(margin-right 而不是 marginRight)

这应该有效,您不需要手动为元素创建每个元素,它是在引擎盖下完成的。

这是

你想要的吗?

<div id="cont">
    <div class="us">asdfafsdf</div>
    <div class="us">343464</div>
    <div class="us">asdfdsfds</div>
</div>

jquery

$('#cont').children(".us").each(function() {
    $(this).mouseenter(function() {
         $(this).animate({marginRight: "10px"}, "fast");
    });
});