在悬停时显示和隐藏上下文

时间:2012-01-15 20:11:50

标签: jquery html

我有很多带有标题标题的div,它包含2个div,一个包含实际标题,另一个包含预览文本。除非你将鼠标悬停在一个标题上,否则我只想显示标题。

所以它看起来像这样:

<div class="headline" data-rating="0.331168021644" onclick="javascript:showArticle(1068);" style="display: none; ">
                        <div class="headline_txt"><h1>‘Rechtse zusterpartij dreigt voor CDA’</h1></div>                     <div class="preview_txt" style="display: none"><p><p>Uit grote onvrede over de ‘linkse’ koers van het CDA zou een deel van de partijleden een afsplitsing beramen. Ze vrezen meer terreinverlies op de momenteel populaire rechtervleugel waarop de VVD en PVV goed gedijen.</p></p></div>                  </div>

我试试这个但是$(这个“headline_txt”)是错误的,我只是不知道如何访问该对象。

$("#headline").hover(
        function() {
            $(this "headline_txt").hide();
            $(this "preview_txt").show();
        },
        function() {
            $(this "headline_txt").show();
            $(this "preview_txt").hide();
        }
    );

2 个答案:

答案 0 :(得分:1)

使用$(this)为悬停元素创建一个jQuery对象,然后在其上使用.find()来搜索子对象以隐藏/显示所需的对象。您的父对象也是一个类,而不是一个id,因此您可以使用.headline作为它的选择器。

$(".headline").hover(
    function() {
        $(this).find(".headline_txt").hide();
        $(this).find(".preview_txt").show();
    },
    function() {
        $(this).find(".headline_txt").show();
        $(this).find(".preview_txt").hide();
    }
);

或保存$(this)稍微提高效率,您可以使用:

$(".headline").hover(
    function() {
        var item = $(this);
        item.find(".headline_txt").hide();
        item.find(".preview_txt").show();
    },
    function() {
        var item = $(this);
        item.find(".headline_txt").show();
        item.find(".preview_txt").hide();
    }
);

答案 1 :(得分:1)

尝试以下方法:

$(".headline").hover( //you need to select the class headline, not the id

function() {
    $(this).children(".headline_txt").hide(); //you select the children of the selected .headline
    $(this).children(".preview_txt").show();
}, function() {
    $(this).children(".headline_txt").show();
    $(this).children(".preview_txt").hide();
});

此外,您需要从display:none移除.headline才能将其悬停。

演示: http://jsfiddle.net/6sQsH/2

更好的是,您可以使用toggle(),这样就不会重复代码。

$(".headline").hover(

function() {
    $(this).children(".headline_txt").toggle();
    $(this).children(".preview_txt").toggle();
});

演示: http://jsfiddle.net/6sQsH/1/

相关问题