首页 > 解决方案 > 如何在视口中更改图像的 src 属性?

问题描述

image-rotate 类有一组元素。这是图像所在的锚点。轮播需要旋转10张图片。

<a href= class="images-rotation" data-images='["img/2.mp4-001.jpg", "img/2.mp4-002.jpg", "img/2.mp4-003.jpg", "img/2.mp4-004.jpg"]'>
    <img src=""img/2.mp4-000.jpg>
</a>

有工作代码可以为鼠标悬停事件执行此操作。当元素进入移动设备的可见区域时,我也需要这样做。我在 Internet 上找到了一个使用视口的示例代码。我不知道如何将它们结合起来。我是 jquery 新手,知识很少。请告诉我,谢谢。

使用 img 旋转的工作代码:

$.fn.imagesRotation = function (options) {
    var defaults = {
            images: [],         // urls to images
            dataAttr: 'images', // html5 data- attribute which contains an array with urls to images
            imgSelector: 'img', // element to change
            interval: 1000,     // ms
            intervalFirst: 500, // first image change, ms
            callback: null      // first argument would be the current image url
        },
        settings = $.extend({}, defaults, options);

    var clearRotationInterval = function ($el) {
            clearInterval($el.data('imagesRotaionTimeout'));
            $el.removeData('imagesRotaionTimeout');
            clearInterval($el.data('imagesRotaionInterval'));
            $el.removeData('imagesRotaionInterval');
        },
        isInViewport = function() {
            var elementTop = $(this).offset().top;
            var elementBottom = elementTop + $(this).outerHeight();

            var viewportTop = $(window).scrollTop();
            var viewportBottom = viewportTop + $(window).height();

            return elementBottom > viewportTop && elementTop < viewportBottom;
        },
        getImagesArray = function ($this) {
            var images = settings.images.length ? settings.images : $this.data(settings.dataAttr);
            return $.isArray(images) ? images : false;
        },
        preload = function (arr) {  // images preloader
            $(arr).each(function () {
                $('<img/>')[0].src = this;
            });
        },
        init = function () {
            var imagesToPreload = [];
            this.each(function () {  // preload next image
                var images = getImagesArray($(this));
                if (images && images.length > 1) {
                    imagesToPreload.push(images[1]);
                }
            });
            preload(imagesToPreload);
        };

    init.call(this);

    this.on('mouseenter.imagesRotation', function () {
        var $this = $(this),
            $img = settings.imgSelector ? $(settings.imgSelector, $this) : null,
            images = getImagesArray($this),
            imagesLength = images ? images.length : null,
            changeImg = function () {
                var prevIndex = $this.data('imagesRotationIndex') || 0,
                    index = (prevIndex + 1 < imagesLength) ? prevIndex + 1 : 0,
                    nextIndex = (index + 1 < imagesLength) ? index + 1 : 0;
                $this.data('imagesRotationIndex', index);
                if ($img && $img.length > 0) {
                    if ($img.is('img')) {
                        $img.attr('src', images[index]);
                    }
                    else {
                        $img.css('background-image', 'url(' + images[index] + ')');
                    }
                }
                if (settings.callback) {
                    settings.callback(images[index]);
                }
                preload([images[nextIndex]]); // preload next image
            };
        if (imagesLength) {
            clearRotationInterval($this); // in case of dummy intervals
            var timeout = setTimeout(function () {
                changeImg();
                var interval = setInterval(changeImg, settings.interval);
                $this.data('imagesRotaionInterval', interval); // store to clear interval on mouseleave
            }, settings.intervalFirst);
            $this.data('imagesRotaionTimeout', timeout);
        }
    }).on('mouseleave.imagesRotation', function () {
        clearRotationInterval($(this));
    }).on('imagesRotationRemove', function () {
        var $this = $(this);
        $this.off('.imagesRotation');
        clearRotationInterval($this);
    });
};

$.fn.imagesRotationRemove = function () {
    this.trigger('imagesRotationRemove');
};

视口检查代码:

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on('resize scroll', function() {
    if ($('#Something').isInViewport()) {
        // do something
    } else {
        // do something else
    }
});

我不明白如何将它们组合在一起...

标签: javascriptjqueryviewport

解决方案


推荐阅读