如何在没有 CSS 的情况下将鼠标悬停在标题上时使缩略图消失

how can I make thumbnail image disappear when the mouse hovers over the title without css?

本文关键字:标题 消失 略图 悬停 CSS 情况下 鼠标      更新时间:2023-09-26

当我将鼠标悬停在图像的div上时,我有一个简单的jQuery代码,可以通过隐藏一张图片并显示另一张图片来更改帖子的缩略图。当我将鼠标悬停在 .thumbs 类中标记的div上时,代码运行良好,但我也想添加一个功能,以便当我将鼠标悬停在标题上时会发生同样的事情并且缩略图会发生变化。

问题是,如果我将.headline添加到jquery选择器,我没有得到我想要的结果,并且当我将鼠标悬停在缩略图上时,图像会发生变化。

我知道为什么会发生这种情况,但不知道如何解决。由于我只想要我悬停在上面的帖子的图像来更改我正在使用$(this),并且由于图像都在.thumbs内部,因此没有问题。但是标题不在.thumbsdiv内,因此当我使用$(this).headline时,就像我在说不存在thumbs.headline一样。我怎么能不把标题放在同一个div里,仍然知道我正在悬停在哪个帖子上?

  $('.thumbs').hover(
        function() {
           console.info('in');
    $(this).children('.first').css('display','none'); 
    $(this).children('.second').css('display','block')
                        },
        function() {
        console.info('out');
    $(this).children('.second').css('display','none'); 
    $(this).children('.first').css('display','block');
                    });

网页代码:

<h2 class='headline'><a href="<?php the_permalink() ?>"><?php the_title() ?></a></h2>
    <?php if ( has_post_thumbnail() ){ ?>
    <a href="<?php the_permalink(); ?>"></a>
<div class='thumbs'>
     <div class='first'><?php the_post_thumbnail()?></div>
     <div class='second'><?php MultiPostThumbnails::the_post_thumbnail(get_post_type(), 'secondary-image');?></div>
                 </div>

如果包装它们不是一种选择,这应该可以工作:

$('.thumbs').each(function () {
    var thisThumbAndHeadline = $(this).add($(this).prevAll('.headline:first'));
    thisThumbAndHeadline.hover(function () {
        console.info('in');    
        thisThumbAndHeadline.children('.first').hide();
        thisThumbAndHeadline.children('.second').show()
    },
    function () {
        console.info('out');
        thisThumbAndHeadline.children('.first').show();
        thisThumbAndHeadline.children('.second').hide();
    }).trigger('mouseout');
})

一个简单的解决方案是将侦听器应用于围绕标题和拇指的包装器。

http://jsfiddle.net/A8UP8/

.HTML

<div class="wrap">
    <h2 class='headline'> ... </h2>
    <div class='thumbs'>
        <div class='first'> ... /div>
        <div class='second'> ... </div>
    </div>
</div>

JavaScript

$('.wrap').hover(
    function() {
        console.info('in');
        $(this).find('.first').css('display','none'); 
        $(this).find('.second').css('display','block')
    },
    function() {
        console.info('out');
        $(this).find('.second').css('display','none'); 
        $(this).find('.first').css('display','block');
    }
)

试试 jQuery:

  • hide()方法隐藏所选元素

  • show()方法显示隐藏的选定元素