javascript - 将新加载的图像添加到卷中的回调函数

标签 javascript jquery

您好,我正在开发一个具有无限滚动脚本的网站,并试图找出如何为图像灯箱添加回调:

http://osvaldas.info/image-lightbox-responsive-touch-friendly

我已经设法让第二页上的图像与图像灯箱一起使用,并使用以下方法使用相同的变量设置它们的样式:

$(function () {
    $('a[data-imagelightbox="d"]').imageLightbox({
        onStart: function () {
            overlayOn();
        },
        onLoadStart: function () {
            captionOff();
            activityIndicatorOn();
        },
        onLoadEnd: function () {
            captionOn();
            activityIndicatorOff();
        },
        onEnd: function () {
            captionOff();
            overlayOff();
            activityIndicatorOff();
        }
    });
});

我的问题是,虽然可以在灯箱中查看“第二页”中的图像,但它们不会添加到图库/卷中供用户循环/导航。当用户查看“第二页”中的图像并尝试循环浏览时,他们只能查看“第一页”中的图像。

有人知道我应该使用什么脚本来在无限滚动加载更多内容后刷新/添加图像吗?提前致谢!!

这是图像灯箱的完整 js:

var cssTransitionSupport = function () {
    var s = document.body || document.documentElement,
        s = s.style;
    if (s.WebkitTransition == '') return '-webkit-';
    if (s.MozTransition == '') return '-moz-';
    if (s.OTransition == '') return '-o-';
    if (s.transition == '') return '';
    return false;
},

    isCssTransitionSupport = cssTransitionSupport() === false ? false : true,

    cssTransitionTranslateX = function (element, positionX, speed) {
        var options = {}, prefix = cssTransitionSupport();
        options[prefix + 'transform'] = 'translateX(' + positionX + ')';
        options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear';
        element.css(options);
    },

    hasTouch = ('ontouchstart' in window),
    hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
    wasTouched = function (event) {
        if (hasTouch) return true;

        if (!hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined') return false;

        if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') {
            if (event.MSPOINTER_TYPE_MOUSE != event.pointerType) return true;
        } else if (event.pointerType != 'mouse') return true;

        return false;
    };

$.fn.imageLightbox = function (options) {
    var options = $.extend({
        selector: 'id="imagelightbox"',
        allowedTypes: 'png|jpg|jpeg|gif',
        animationSpeed: 250,
        preloadNext: true,
        enableKeyboard: true,
        quitOnEnd: false,
        quitOnImgClick: false,
        quitOnDocClick: true,
        onStart: false,
        onEnd: false,
        onLoadStart: false,
        onLoadEnd: false
    },
                           options),

        targets = $([]),
        target = $(),
        image = $(),
        imageWidth = 0,
        imageHeight = 0,
        swipeDiff = 0,
        inProgress = false,

        isTargetValid = function (element) {
            return $(element).prop('tagName').toLowerCase() == 'a' && (new RegExp('\.(' + options.allowedTypes + ')$', 'i')).test($(element).attr('href'));
        },

        setImage = function () {
            if (!image.length) return true;

            var screenWidth = $(window).width() * 0.8,
                screenHeight = $(window).height() * 0.9,
                tmpImage = new Image();

            tmpImage.src = image.attr('src');
            tmpImage.onload = function () {
                imageWidth = tmpImage.width;
                imageHeight = tmpImage.height;

                if (imageWidth > screenWidth || imageHeight > screenHeight) {
                    var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
                    imageWidth /= ratio;
                    imageHeight /= ratio;
                }

                image.css({
                    'width': imageWidth + 'px',
                    'height': imageHeight + 'px',
                    'top': ($(window).height() - imageHeight) / 2 + 'px',
                    'left': ($(window).width() - imageWidth) / 2 + 'px'
                });
            };
        },

        loadImage = function (direction) {
            if (inProgress) return false;

            direction = typeof direction === 'undefined' ? false : direction == 'left' ? 1 : -1;

            if (image.length) {
                if (direction !== false && (targets.length < 2 || (options.quitOnEnd === true && ((direction === -1 && targets.index(target) == 0) || (direction === 1 && targets.index(target) == targets.length - 1))))) {
                    quitLightbox();
                    return false;
                }
                var params = {
                    'opacity': 0
                };
                if (isCssTransitionSupport) cssTransitionTranslateX(image, (100 * direction) - swipeDiff + 'px', options.animationSpeed / 1000);
                else params.left = parseInt(image.css('left')) + 100 * direction + 'px';
                image.animate(params, options.animationSpeed, function () {
                    removeImage();
                });
                swipeDiff = 0;
            }

            inProgress = true;
            if (options.onLoadStart !== false) options.onLoadStart();

            setTimeout(function () {
                image = $('<img ' + options.selector + ' />')
                .attr('src', target.attr('href'))
                .load(function () {
                    image.appendTo('body');
                    setImage();

                    var params = {
                        'opacity': 1
                    };

                    image.css('opacity', 0);
                    if (isCssTransitionSupport) {
                        cssTransitionTranslateX(image, -100 * direction + 'px', 0);
                        setTimeout(function () {
                            cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000)
                        }, 50);
                    } else {
                        var imagePosLeft = parseInt(image.css('left'));
                        params.left = imagePosLeft + 'px';
                        image.css('left', imagePosLeft - 100 * direction + 'px');
                    }

                    image.animate(params, options.animationSpeed, function () {
                        inProgress = false;
                        if (options.onLoadEnd !== false) options.onLoadEnd();
                    });
                    if (options.preloadNext) {
                        var nextTarget = targets.eq(targets.index(target) + 1);
                        if (!nextTarget.length) nextTarget = targets.eq(0);
                        $('<img />').attr('src', nextTarget.attr('href')).load();
                    }
                })
                .error(function () {
                    if (options.onLoadEnd !== false) options.onLoadEnd();
                })

                var swipeStart = 0,
                    swipeEnd = 0,
                    imagePosLeft = 0;

                image.on(hasPointers ? 'pointerup MSPointerUp' : 'click', function (e) {
                    e.preventDefault();
                    if (options.quitOnImgClick) {
                        quitLightbox();
                        return false;
                    }
                    if (wasTouched(e.originalEvent)) return true;
                    var posX = (e.pageX || e.originalEvent.pageX) - e.target.offsetLeft;
                    target = targets.eq(targets.index(target) - (imageWidth / 2 > posX ? 1 : -1));
                    if (!target.length) target = targets.eq(imageWidth / 2 > posX ? targets.length : 0);
                    loadImage(imageWidth / 2 > posX ? 'left' : 'right');
                })
                .on('touchstart pointerdown MSPointerDown', function (e) {
                    if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
                    if (isCssTransitionSupport) imagePosLeft = parseInt(image.css('left'));
                    swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
                })
                .on('touchmove pointermove MSPointerMove', function (e) {
                    if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
                    e.preventDefault();
                    swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
                    swipeDiff = swipeStart - swipeEnd;
                    if (isCssTransitionSupport) cssTransitionTranslateX(image, -swipeDiff + 'px', 0);
                    else image.css('left', imagePosLeft - swipeDiff + 'px');
                })
                .on('touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', function (e) {
                    if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
                    if (Math.abs(swipeDiff) > 50) {
                        target = targets.eq(targets.index(target) - (swipeDiff < 0 ? 1 : -1));
                        if (!target.length) target = targets.eq(swipeDiff < 0 ? targets.length : 0);
                        loadImage(swipeDiff > 0 ? 'right' : 'left');
                    } else {
                        if (isCssTransitionSupport) cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
                        else image.animate({
                            'left': imagePosLeft + 'px'
                        }, options.animationSpeed / 2);
                    }
                });

            }, options.animationSpeed + 100);
        },

        removeImage = function () {
            if (!image.length) return false;
            image.remove();
            image = $();
        },

        quitLightbox = function () {
            if (!image.length) return false;
            image.animate({
                'opacity': 0
            }, options.animationSpeed, function () {
                removeImage();
                inProgress = false;
                if (options.onEnd !== false) options.onEnd();
            });
        };

    $(window).on('resize', setImage);

    if (options.quitOnDocClick) {
        $(document).on(hasTouch ? 'touchend' : 'click', function (e) {
            if (image.length && !$(e.target).is(image)) quitLightbox();
        })
    }

    if (options.enableKeyboard) {
        $(document).on('keyup', function (e) {
            if (!image.length) return true;
            e.preventDefault();
            if (e.keyCode == 27) quitLightbox();
            if (e.keyCode == 37 || e.keyCode == 39) {
                target = targets.eq(targets.index(target) - (e.keyCode == 37 ? 1 : -1));
                if (!target.length) target = targets.eq(e.keyCode == 37 ? targets.length : 0);
                loadImage(e.keyCode == 37 ? 'left' : 'right');
            }
        });
    }

    $(document).on('click', this.selector, function (e) {
        if (!isTargetValid(this)) return true;
        e.preventDefault();
        if (inProgress) return false;
        inProgress = false;
        if (options.onStart !== false) options.onStart();
        target = $(this);
        loadImage();
    });

    this.each(function () {
        if (!isTargetValid(this)) return true;
        targets = targets.add($(this));
    });

    this.switchImageLightbox = function (index) {
        var tmpTarget = targets.eq(index);
        if (tmpTarget.length) {
            var currentIndex = targets.index(target);
            target = tmpTarget;
            loadImage(index < currentIndex ? 'left' : 'right');
        }
        return this;
    };

    this.quitImageLightbox = function () {
        quitLightbox();
        return this;
    };

    return this;
};

最佳答案

首先

$(function () {
    window.lightbox = $('a[data-imagelightbox="d"]').imageLightbox();
});

在“imagelightbox.js”的末尾,添加以下代码。

this.quitImageLightbox = function() {
    quitLightbox();
    return this;
};

this.loadImages = function(images_array) {
    targets = images_array;
    console.log(targets);
    console.log(targets.length);
    return this;
};

当你获得新加载的图像时

windows.lightbox.loadImages(images_array)

它应该可以工作......!

关于javascript - 将新加载的图像添加到卷中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24933828/

相关文章:

jquery - 如何制作iframe的灯箱 'breakout'?

javascript - 如何根据2个键获取不同的数组列表?

javascript - d3 图缺少数组中的第一项

jquery - 使用 jQuery UI 启用在叠加层下方的元素中拖动

javascript - 无法使用放置在 Ruby on Rails vendor 文件夹中的 jQuery 插件

javascript - jqGrid ('getGridParam' ,'colNames' )奇怪的行为

javascript - 使用 jQuery 从 JSON 文件中提取数据并将其分成组

javascript - jQuery 可以将 cookie 读/写到浏览器吗?

javascript - 如何仅在悬停而不设置样式时禁用 classList

javascript - 根据下拉选择向表单添加和删除输入标签