Jquery影响具有相同名称的所有元素

时间:2012-02-04 18:00:15

标签: javascript jquery elements

这是我的html文件中的代码:

    <div id="centerBlock">
        <block>
            <site style="padding-top: 10px; margin-left: 20px">
                <img src="./images/site1.png" alt="some_text"/>
            </site>
            <textOnImage style="padding-top: 10px; margin-left: 20px">
                lolol
            </textOnImage>
        </block>

        <block>
            <site style="padding-top: 163px; margin-left: 20px">
                <img src="./images/site1.png" alt="some_text"/>
            </site>
            <textOnImage style="padding-top: 163px; margin-left: 20px">
                lolol
            </textOnImage>
        </block>

    </div>

这是我的javascript:

$("block").mouseenter(function(){        
    $("site").fadeTo("slow", 0.25);
    $("textOnImage").animate({ 
        opacity: "1"
    }, 600 );
});

$("block").mouseleave(function(){         
    $("site").fadeTo("slow", 1);
    $("textOnImage").animate({ 
        opacity: "0"
    }, 600 );
 });

但是,当我将鼠标悬停在两个块元素中的一个上时,它们都会向下移动,当我将鼠标移开时,它们都会返回原始状态。我搜索了几个小时,我100%肯定我一直在搜索错误的条款。我该如何单独进行?

3 个答案:

答案 0 :(得分:4)

使用this仅定位触发事件的块,然后使用.find()在该特定块中查找所需的元素。你之前的做法显然是在整个页面中找到所有site元素和所有textOnImage元素,而不仅仅是触发事件的块中的元素。

$("block").mouseenter(function(){        
    var $this = $(this);
    $this.find("site").fadeTo("slow", 0.25);
    $this.find("textOnImage").animate({ 
        opacity: "1"
    }, 600 );
});

$("block").mouseleave(function(){         
    var $this = $(this);
    $this.find("site").fadeTo("slow", 1);
    $this.find("textOnImage").animate({ 
        opacity: "0"
    }, 600 );
 });

答案 1 :(得分:2)

您需要遍历悬停元素的结构。您可以像这样使用.find() ......

$("block").mouseenter(function(){        
    $(this).find("site").fadeTo("slow", 0.25);
    $(this).find("textOnImage").animate({ 
        opacity: "1"
    }, 600 );
});

$("block").mouseleave(function(){         
    $(this).find("site").fadeTo("slow", 1);
    $(this).find("textOnImage").animate({ 
        opacity: "0"
    }, 600 );
 });

在事件处理程序中,this是对处理程序绑定到的元素的引用。

您也可以使用.children()代替.find(),因为目标元素只有一层深度。


旁注,你可以使用.hover(),并传递两个这样的函数..

$("block").hover(function(){        
    $(this).find("site").fadeTo("slow", 0.25);
    $(this).find("textOnImage").animate({ 
        opacity: "1"
    }, 600 );
},
  function(){         
    $(this).find("site").fadeTo("slow", 1);
    $(this).find("textOnImage").animate({ 
        opacity: "0"
    }, 600 );
});

您可能还希望在.stop()fadeTo来电之前添加一些animate来电,否则当您快速鼠标悬停时,动画将会在队列中。

答案 2 :(得分:2)

试试这个(向jquery选择器提供this上下文以定位特定元素):

$("block").mouseenter(function(){        
    $("site", this).fadeTo("slow", 0.25);
    $("textOnImage", this).animate({ 
        opacity: "1"
    }, 600 );
});

$("block").mouseleave(function(){         
    $("site", this).fadeTo("slow", 1);
    $("textOnImage", this).animate({ 
        opacity: "0"
    }, 600 );
 });
相关问题