在jQuery中只选择整个css类的一个div

时间:2014-08-15 17:06:34

标签: javascript jquery html css html5

我的目标是在div悬停时在div上显示叠加层。普通div称为.circleBase.type1,叠加层为circleBase.overlay。我的页面上有多个这些div。当我将鼠标悬停在一个.cirlceBase.type1上时,每个.circleBase.type1都会显示叠加层。我该如何防止这种情况?

以下是一些代码:

HTML

<div class="circleBase type1">
    <p class="hidetext">Lorem ipsum</p>
    <hr size="10">
    <strong class="gray hidetext">gdroel</strong>
</div>
<div class="circleBase overlay">
   <p class="date">11/12/14</p>
</div>

和jQuery

$(document).ready(function(){
    $('.overlay').hide();
    $('.date').hide();

    $(".circleBase.type1").mouseenter(function(){
        $(".overlay").fadeIn("fast");
        $('.date').show();
        $('.hidetext').hide();
    });

    $(".overlay").mouseleave(function(){
        $(this).fadeOut("fast");
        $('.date').hide();
        $('.hidetext').show();
    });
});

3 个答案:

答案 0 :(得分:2)

使用$(this)获取当前元素引用,并执行以下操作:

$(".circleBase.type1").mouseenter(function(){
    $(this).next(".overlay").fadeIn("fast");
    $(this).next(".overlay").find('.date').show();
    $(this).find('.hidetext').hide();
});

$(".overlay").mouseleave(function(){
        $(this).fadeOut("fast");
        $(this).find('.date').hide();
        $(this).prev(".circleBase").find('.hidetext').show();
    });

答案 1 :(得分:0)

通常当我想针对特定内容时,您只需为其提供 ID

ID在JavaScript中比在类中更好。

如果您有一个特定的容器,那么使用容器作为起点也是一条好路线

$('#container').find('.something.type1').doSomething();

这对于jquery来说效率要高得多,因为它只搜索#container中的.something.type1。

答案 2 :(得分:0)

嗯,我不确定你想要做什么,但看起来你想要用悬停文本替换某种圆圈中的内容,但是要淡化。要做到这一点,你必须添加一些CSS,最好也改变你的HTML结构。

HTML应如下所示:

<div class="circleContainer">
    <div class="circleBase">
        <p>Lorem ipsum</p>
        <hr>
        <strong class="gray">gdroel</strong>
    </div>
    <div class="overlay" style="display: none;">
       <p class="date">11/12/14</p>
    </div>
</div>

所以你的js看起来像这样:

$(function(){
    $(".circleContainer").mouseenter(function(){
        $(this).find(".overlay")
        $(this).find('.circleBase').hide();
    });

    $(".circleContainer").mouseleave(function(){
        $(this).find('.circleBase').show();
        $(this).find(".overlay").hide();
    });
});

Here's a working solution包含一些CSS以使其更好。尝试将其取出并运行它,您将立即看到问题。