JQuery обмен изображениями при наведении с подписью - PullRequest
0 голосов
/ 27 января 2012

У меня есть черно-белые изображения.Когда вы наводите курсор мыши на изображение, оно превращается в цветное изображение, которое представляет собой отдельный файл (img-1.png и hover-img-1.png и т. Д.).Существует также заголовок, который всегда должен отображаться поверх изображений в виде абсолютного позиционного элемента.

Моя проблема заключается в том, что изображение поменяется местами, но когда я наведу указатель мыши на заголовок, изображение возвращается к b /w вместо того, чтобы оставаться в цвете.

Что мне не хватает?

Вот код, который у меня сейчас есть:

    <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<style>
    .galleryImg {
        float:left;
        margin: 10px 4px;
        position:relative;
    }
    .caption {
        position: absolute;
        bottom: 10px;
        right: 15px;
        text-transform:uppercase;
        font-size:14px;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type="text/javascript">
<!--

    // wrap as a jQuery plugin and pass jQuery in to our anoymous function
    (function ($) {
        $.fn.cross = function (options) {
            return this.each(function (i) { 
                // cache the copy of jQuery(this) - the start image
                var $$ = $(this);

                // get the target from the backgroundImage + regexp
                var target = $$.css('backgroundImage').replace(/^url|[\(\)'"]/g, '');

                // nice long chain: wrap img element in span
                $$.wrap('<span style="position: relative;"></span>')
                    // change selector to parent - i.e. newly created span
                    .parent()
                    // prepend a new image inside the span
                    .prepend('<img>')
                    // change the selector to the newly created image
                    .find(':first-child')
                    // set the image to the target
                    .attr('src', target);

                // the CSS styling of the start image needs to be handled
                // differently for different browsers
                if ($.browser.msie || $.browser.mozilla) {
                    $$.css({
                        'position' : 'absolute', 
                        'left' : 0,
                        'background' : '',
                        'top' : this.offsetTop
                    });
                } else if ($.browser.opera && $.browser.version < 9.5) {
                    // Browser sniffing is bad - however opera < 9.5 has a render bug 
                    // so this is required to get around it we can't apply the 'top' : 0 
                    // separately because Mozilla strips the style set originally somehow...                    
                    $$.css({
                        'position' : 'absolute', 
                        'left' : 0,
                        'background' : '',
                        'top' : "0"
                    });
                } else { // Safari
                    $$.css({
                        'position' : 'absolute', 
                        'left' : 0,
                        'background' : ''
                    });
                }

                // similar effect as single image technique, except using .animate 
                // which will handle the fading up from the right opacity for us
                $$.hover(function () {
                    $$.stop().animate({
                        opacity: 0
                    }, 250);
                }, function () {
                    $$.stop().animate({
                        opacity: 1
                    }, 250);
                });
            });
        };

    })(jQuery);

    // note that this uses the .bind('load') on the window object, rather than $(document).ready() 
    // because .ready() fires before the images have loaded, but we need to fire *after* because
    // our code relies on the dimensions of the images already in place.
    jQuery(window).bind('load', function () {
        jQuery('img.fade').cross();
    });

    //-->
</script>    
</head>

<body>
<div class="galleryImg">
    <a href="some_link">
        <img src="images/img-1.png" alt="" title="" class="fade" style="background: url(images/hover-img-1.png);" />
        <div class="caption">This is Image 1</div>
    </a>
</div>
<div class="galleryImg">
    <a href="some_link">
        <img src="images/img-2.png" alt="" title="" class="fade" style="background: url(images/hover-img-2.png);" />
        <div class="caption">This is Image 2</div>
    </a>
</div>
<div class="galleryImg">
    <a href="some_link">
        <img src="images/img-2.png" alt="" title="" class="fade" style="background: url(images/hover-img-2.png);" />
        <div class="caption">This is Image 3</div>
    </a>
</div>
</body>

1 Ответ

2 голосов
/ 27 января 2012

Возможно, потому что div.caption покрывает изображение и не является потомком изображения, на котором зарегистрирован обработчик события наведения мыши.

Оберните img и div.caption в div.Something и зарегистрируйте обработчик наведения на div.Something вместо изображения.Или, на самом деле, вы можете просто зарегистрировать обработчик на <a>, который уже оборачивает их;)

Не знаю, насколько «правильно» модифицировать плагин, чтобы сделать это, но самое быстрое исправлениев этом случае можно изменить

        $$.hover(function () {
            $$.stop().animate({
                opacity: 0
            }, 250);
        }, function () {
            $$.stop().animate({
                opacity: 1
            }, 250);
        });

на

        $$.closest('.galleryImg').hover(function () {
            $$.stop().animate({
                opacity: 0
            }, 250);
        }, function () {
            $$.stop().animate({
                opacity: 1
            }, 250);
        });

Обновление: исправлено использование .closest('.galleryImg') вместо .parent().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...