【问题标题】:Jquery-CSS bug fixJquery-CSS 错误修复
【发布时间】:2011-07-19 17:24:36
【问题描述】:

我有以下 HTML 结构:

<ul>
    <li><a href><img src/></a></li>
    <li><a href><img src/></a></li>
    <li><a href><img src/></a></li>
</ul>

由于修复了一些 CSS 错误,我需要知道哪些图片链接是“鼠标悬停”的 然后在 Jquery 脚本中我需要选择器,类似于

$('a img').mouseover(function(){
var imgElement = $(this);
if ('a img[3]') { // if the hovered link is the third
imgElement.animate({
                width: "315px",
                height: "225px",
                marginLeft: "-150px"
            }, 1500 );

问题是在这种情况下如何获得第二个或第三个'a img'。

【问题讨论】:

    标签: javascript jquery html image html-lists


    【解决方案1】:

    试试这个

    $('a img').each(function(i){
     $(this).mouseover(function(){
        if (i == 2) { // if the hovered link is the third
          $(this).animate({
                    width: "315px",
                    height: "225px",
                    marginLeft: "-150px"
                }, 1500 );
         }
      });
    });
    

    【讨论】:

    • 为什么不把if移到外面。现在 所有 元素都有一个事件绑定,除了一个之外,所有元素都不做任何事情。
    • 我想他可能对其他图像有不同的条件,所以我们需要在 mouseover 事件中使用它,否则可以将其移出。
    【解决方案2】:

    试试这个http://jsfiddle.net/pxfunc/M2KAF/

    var $imgs = $('a img');
    $imgs.mouseover(function() {
        var $that = $(this);
        if ($imgs.index($that) === 2) { // if the hovered link is the third
            $that.animate({
                width: "315px",
                height: "225px",
                marginLeft: "-150px"
            }, 1500);
        }
    });
    

    【讨论】:

      【解决方案3】:

      我会使用 jquery 的第 n 个子选择器 http://api.jquery.com/nth-child-selector/

      【讨论】:

        【解决方案4】:

        我不确定我是否正确地关注了你。如果你想要第三个&lt;li&gt;&lt;img&gt;,你可以使用$('ul li:eq(2) a img')

        【讨论】:

        • 我认为应该是 :eq(2) 或 :nth-child(3)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 2013-09-20
        • 2021-09-11
        • 2017-01-03
        • 2011-09-11
        相关资源
        最近更新 更多