【问题标题】:Accessing a changed DOM element访问已更改的 DOM 元素
【发布时间】:2014-10-27 20:00:12
【问题描述】:

有没有办法访问 JS 更改的 DOM 元素?我有一个图像框,它根据使用 JS/JQ 更改缩略图而改变。

我有第二个 javascript,它是放大图像的放大镜。但是,它只是放大了原始 src 链接,div 内的原始 src,而不是更改后的 src 链接。

在调试器中,我可以看到 div 元素中的图像变化,但放大镜脚本看不到它。放大镜脚本似乎只是在访问 div 元素的原始 src。

这两个 JS/JQ 脚本都是由不同的人编写的,我正在努力让它们很好地协同工作。

我是 JS 新手,所以我不确定这是否可行。

这是正在更改的 HTML(图库 JS 更改了 src 元素):

 <img class="picture-slides-image"  src="artifactImages/bowl_fragment_16134_04E.jpg" alt=""/ >

这是设置放大镜的 HTML 中的 JS:

                <script>
                 $('.picture-slides-image').ClassyLoupe({
                    maxSize: 600,
                    size: 300,
                    minSize: 200,
                    loupeToggleSpeed: 'fast'
                 });
                </script>

这是放大镜的 JS:

(function($) {
    var id = 0;
    jQuery.fn.ClassyLoupe = function(a) {
        id++;
        if (this.length > 1) {
            return this.each(function() {
                $(this).ClassyLoupe(a);
            }), this;
        }
        var a = $.extend({
            trigger: 'mouseenter',
            shape: 'circle',
            roundedCorners: 10,
            loupeToggleSpeed: 'medium',
            loupeToggleEasing: 'linear',
            size: 200,
            minSize: 150,
            maxSize: 250,
            glossy: true,
            shadow: true,
            resize: true,
            sizeSnap: 10,
            resizeAnimationSpeed: 'medium',
            resizeAnimationEasing: 'easeOutBack',
            canZoom: true,
            zoomKey: 90,
            zoom: 100,
            minZoom: 50,
            maxZoom: 200,
            zoomSnap: 5,
            zoomAnimationSpeed: 'medium',
            zoomAnimationEasing: 'easeOutBack',
            overlay: true,
            overlayOpacity: 0.5,
            overlayEffectSpeed: 'slow',
            overlayEffectEasing: 'easeOutBack',
            overlayClassName: ''
        }, a || {}), j = jQuery(this), c = 'classyloupe-' + id, t = 'classyloupe_overlay-' + id, h = a.size, i, q = null, u = 0, v = 0, x = 0, y = 0, r = 0, s = 0, w = false, p = false, k = a.zoom, n = 0, o = 0, e, z = false;
        return this.each(function() {
            function A() {
                var d = h - 2 * $('#' + c + ' .lglossy').css('marginTop'), e = h / 2, g = 0, f = 0;
                a.shape === 'circle' ? f = g = e : a.shape === 'rounded' && (g = parseInt($('#' + c).css('border-top-width')), f = g = a.roundedCorners - g);
                $('#' + c + ' .glossy').stop().animate({
                    width: d + 'px',
                    height: e + 'px',
                    '-webkit-border-top-left-radius': g + 'px',
                    '-webkit-border-top-right-radius': f + 'px',
                    '-moz-border-radius-topleft': g + 'px',
                    '-moz-border-radius-topright': f + 'px',
                    'border-top-left-radius': g + 'px',
                    'border-top-right-radius': f + 'px'
                }, {
                    queue: false,
                    easing: a.resizeAnimationEasing,
                    duration: a.resizeAnimationSpeed
                });
            }
            function B(d, e) {
                if (w && a.canZoom) {
                    if (!(k + a.zoomSnap * d > a.maxZoom || k + a.zoomSnap * d < a.minZoom)) {
                        k += a.zoomSnap * d;
                        r += Math.round(x * a.zoomSnap / 100) * d;
                        s += Math.round(y * a.zoomSnap / 100) * d;
                        var g = e.pageY - this.offsetTop;
                        n = Math.round(r / u * (e.pageX - this.offsetLeft)) * -1 + h / 2;
                        o = Math.round(s / v * g) * -1 + h / 2;
                        $('#' + c).animate({
                            'background-position': n + 'px ' + o + 'px',
                            'background-size': r + 'px ' + s + 'px'
                        }, {
                            queue: false,
                            easing: a.zoomAnimationEasing,
                            duration: a.zoomAnimationSpeed,
                            complete: function() {
                                i = $('#' + c).outerWidth();
                                var a = new jQuery.Event('mousemove', {
                                    pageX: m + i / 2,
                                    pageY: l + i / 2
                                });
                                j.trigger(a);
                            }
                        });
                    }
                }
                else if (a.resize && !w && (g = d * a.sizeSnap, !(h + g > a.maxSize || h + g < a.minSize))) {
                    h += g;
                    var f = 0, m = Math.round($('#' + c).offset().left - g), l = Math.round($('#' + c).offset().top - g);
                    n += g;
                    o += g;
                    $('#' + c).stop();
                    a.shape === 'circle' ? (f = h / 2, $('#' + c).animate({
                        width: h + 'px',
                        height: h + 'px',
                        '-webkit-border-top-left-radius': f + 'px',
                        '-webkit-border-top-right-radius': f + 'px',
                        '-webkit-border-bottom-left-radius': f + 'px',
                        '-webkit-border-bottom-right-radius': f + 'px',
                        '-moz-border-radius-topleft': f + 'px',
                        '-moz-border-radius-topright': f + 'px',
                        '-moz-border-radius-bottomleft': f + 'px',
                        '-moz-border-radius-bottomright': f + 'px',
                        'border-top-left-radius': f + 'px',
                        'border-top-right-radius': f + 'px',
                        'border-bottom-left-radius': f + 'px',
                        'border-bottom-right-radius': f + 'px',
                        'background-position': n + 'px ' + o + 'px',
                        left: m + 'px',
                        top: l + 'px'
                    }, {
                        queue: false,
                        easing: a.resizeAnimationEasing,
                        duration: a.resizeAnimationSpeed,
                        complete: function() {
                            i = $('#' + c).outerWidth();
                            var a = new jQuery.Event('mousemove', {
                                pageX: m + i / 2,
                                pageY: l + i / 2
                            });
                            j.trigger(a);
                        }
                    })) : a.shape === 'rounded' ? $('#' + c).animate({
                        width: h + 'px',
                        height: h + 'px',
                        '-webkit-border-radius': a.roundedCorners,
                        '-moz-border-radius': a.roundedCorners,
                        'border-radius': a.roundedCorners,
                        'background-position': n + 'px ' + o + 'px',
                        left: m + 'px',
                        top: l + 'px'
                    }, {
                        queue: false,
                        easing: a.resizeAnimationEasing,
                        duration: a.resizeAnimationSpeed,
                        complete: function() {
                            i = $('#' + c).outerWidth();
                            var a = new jQuery.Event('mousemove', {
                                pageX: m + i / 2,
                                pageY: l + i / 2
                            });
                            j.trigger(a);
                        }
                    }) : a.shape === 'square' && $('#' + c).animate({
                        width: h + 'px',
                        height: h + 'px',
                        'background-position': n + 'px ' + o + 'px',
                        left: m + 'px',
                        top: l + 'px'
                    }, {
                        queue: false,
                        easing: a.resizeAnimationEasing,
                        duration: a.resizeAnimationSpeed,
                        complete: function() {
                            i = $('#' + c).outerWidth();
                            var a = new jQuery.Event('mousemove', {
                                pageX: m + i / 2,
                                pageY: l + i / 2
                            });
                            j.trigger(a);
                        }
                    });
                    a.glossy && A();
                }
            }
            (function() {
                j.is("a") ? (q = j.attr('href'), e = j.find('img')) : (j.is('img') || j.is('input[type="image"]')) && (q = j.attr('src'), e = j);
                u = e.width();
                v = e.height();
                $('body').append('<div class="classyloupe" id="' + c + '"></div>');
                var d = new Image;
                d.onload = function() {
                    x = this.width;
                    y = this.height;
                    r = Math.round(x * k / 100);
                    s = Math.round(y * k / 100);
                    var d = h / 2;
                    $('#' + c).css({
                        width: h + 'px',
                        height: h + 'px',
                        'background-image': 'url(' + q + ')',
                        'background-size': r + 'px ' + s + 'px'
                    });
                    a.shape === 'circle' ? $('#' + c).css({
                        '-webkit-border-radius': d + 'px',
                        '-moz-border-radius': d + 'px',
                        'border-radius': d + 'px'
                    }) : a.shape === 'rounded' && $('#' + c).css({
                        '-webkit-border-radius': a.roundedCorners,
                        '-moz-border-radius': a.roundedCorners,
                        'border-radius': a.roundedCorners + 'px'
                    });
                    i = $('#' + c).outerWidth();
                    a.glossy && $('#' + c).append('<div class="lglossy"></div>');
                    a.overlay && ($('body').append("<div class='loverlay " + a.overlayClassName + "' id='" + t + "'></div>"), $('#' + t).css({
                        top: e.offset().top + 'px',
                        left: e.offset().left + 'px',
                        width: e.outerWidth() + 'px',
                        height: e.outerHeight() + 'px'
                    }));
                    a.shadow && $('#' + c).addClass('lshadow');
                };
                d.src = q;
            }(), (a.resize || a.canZoom) && !z && $.event.special.mousewheel && $('#' + c).bind('mousewheel', function(a, b) {
                B(b, a);
                return false;
            }), e.bind(a.trigger, function(d) {
                p ? ($('#' + c).fadeOut(a.loupeToggleSpeed, a.loupeToggleEasing), p = false, a.overlay && $('#' + t).fadeOut(a.overlayEffectSpeed, a.overlayEffectEasing)) : ($('#' + c).fadeIn(a.loupeToggleSpeed, a.loupeToggleEasing), p = true, a.overlay && $('#' + t).fadeTo(a.overlayEffectSpeed, a.overlayOpacity, a.overlayEffectEasing), A());
                if (d.type === 'click') {
                    return d.preventDefault ? d.preventDefault() : d.returnValue = false, false;
                }
            }), $('#' + c).bind('click', function() {
                e.trigger('click');
            }), $(document).bind('mousemove', function(d) {
                if (!p) {
                    return true;
                }
                var j = parseInt(e.css('border-left-width')) + parseInt(e.css('padding-left')),
                        g = parseInt(e.css('border-top-width')) + parseInt(e.css('padding-top')),
                        f = parseInt(e.css('border-right-width')) + parseInt(e.css('padding-right')),
                        m = parseInt(e.css('border-bottom-width')) + parseInt(e.css('padding-bottom')),
                        l = d.pageX - e.offset().left - j,
                        k = d.pageY - e.offset().top - g,
                        q = Math.round(d.pageX - i / 2),
                        d = Math.round(d.pageY - i / 2);
                n = Math.round(r / u * l) * -1 + h / 2;
                o = Math.round(s / v * k) * -1 + h / 2;
                $('#' + c).css({
                    'background-position': n + 'px ' + o + 'px'
                });
                $('#' + c).css({
                    left: q + 'px',
                    top: d + 'px'
                });
                if (l < -j || k < -g || l > u + f || k > v + m) {
                    $('#' + c).fadeOut(a.loupeToggleSpeed), p = false, a.overlay && $('#' + t).fadeOut(a.overlayEffectSpeed);
                }
            }), $(document).keyup(function(event) {
                if (event.which == a.zoomKey && p) {
                    return w = false, event.preventDefault ? event.preventDefault() : event.returnValue = false, false;
                }
            }).keydown(function(event) {
                if (event.which == a.zoomKey && p) {
                    return w = true, event.preventDefault ? event.preventDefault() : event.returnValue = false, false;
                }
            }));
        });
    };
})(jQuery);

这是画廊的 JS:

jQuery.PictureSlides = function () {
    var useMSFilter = false,
        slideshows = [],
        set = function (settings) {
            slideshows.push(settings);
        },

        init = function () {
            var counter = 0;
            $(".picture-slides-container").each(function () {
                var elm = $(this),

                    // Element references
                    settings = slideshows[counter++],
                    mainImage = elm.find("." + settings.mainImageClass),
                    mainImageFailedToLoad = elm.find("." + settings.mainImageFailedToLoadClass),
                    imageLink = elm.find("." + settings.imageLinkClass),
                    fadeContainer = elm.find("." + settings.fadeContainerClass),
                    imageTextContainer = elm.find("." + settings.imageTextContainerClass),
                    previousLink = elm.find("." + settings.previousLinkClass),
                    nextLink = elm.find("." + settings.nextLinkClass),
                    imageCounter = elm.find("." + settings.imageCounterClass),
                    startSlideShowLink = elm.find("." + settings.startSlideShowClass),
                    stopSlideShowLink = elm.find("." + settings.stopSlideShowClass),
                    thumbnailContainer = elm.find("." + settings.thumbnailContainerClass),
                    thumbnailEvent = settings.thumbnailActivationEvent,
                    thumbnailLinks,
                    dimBackgroundOverlay = $("." + settings.dimBackgroundOverlayClass),

                    // General image settings
                    usePreloading = settings.usePreloading,
                    useAltAsTooltip = settings.useAltAsTooltip,
                    useTextAsTooltip = settings.useTextAsTooltip,
                    images = settings.images,
                    startIndex = (settings.startIndex > 0)? (settings.startIndex - 1) : settings.startIndex,
                    imageIndex = startIndex,
                    currentImageIndex = imageIndex,
                    startSlideShowFromBeginning = settings.startSlideShowFromBeginning,
                    dimBackgroundAtLoad = settings.dimBackgroundAtLoad,

                    // General fade settings
                    useFadingIn = settings.useFadingIn,
                    useFadingOut = settings.useFadingOut,
                    useFadeWhenNotSlideshow = settings.useFadeWhenNotSlideshow,
                    useFadeForSlideshow = settings.useFadeForSlideshow,
                    useDimBackgroundForSlideshow = settings.useDimBackgroundForSlideshow,
                    loopSlideshow = settings.loopSlideshow,
                    fadeTime = settings.fadeTime,
                    timeForSlideInSlideshow = settings.timeForSlideInSlideshow,
                    startSlideshowAtLoad = settings.startSlideshowAtLoad,
                    slideshowPlaying = false,
                    timer,

                    // Sets main image
                    setImage = function () {
                        // Set main image values
                        var imageItem = images[imageIndex];
                        mainImage.attr({
                            src : imageItem.image,
                            alt : imageItem.alt
                        });

                        // If the alt text should be used as the tooltip
                        if (useAltAsTooltip) {
                            mainImage.attr("title", imageItem.alt);
                        }

                        // If the image text should be used as the tooltip
                        if (useTextAsTooltip) {
                            mainImage.attr("title", imageItem.text);
                        }

                        // Set image text
                        if (imageTextContainer.length > 0) {
                            imageTextContainer.text(imageItem.text);
                        }

                        // Set image link
                        if (imageLink.length > 0) {
                            var url = imageItem.url;
                            if (typeof url !== "undefined" && url.length > 0) {
                                imageLink.attr("href", imageItem.url);
                            }
                            else {
                                imageLink.removeAttr("href");
                            }   
                        }

                        // Set image counter values
                        if (imageCounter.length > 0) {
                            imageCounter.text((imageIndex + 1) + "/" + (images.length));
                        }

                        if (!loopSlideshow) {
                            // Enabling/disabling previous link
                            if (imageIndex === 0) {
                                previousLink.addClass("picture-slides-disabled");
                            }
                            else {
                                previousLink.removeClass("picture-slides-disabled");
                            }

                            // Enabling/disabling next link
                            if (imageIndex === (images.length - 1)) {
                                nextLink.addClass("picture-slides-disabled");
                            }
                            else {
                                nextLink.removeClass("picture-slides-disabled");
                            }
                        }

                        // Keeping a reference to the current image index
                        currentImageIndex = imageIndex;

                        // Adding/removing classes from thumbnail
                        if (thumbnailContainer[0]) {                            
                            thumbnailLinks.removeClass("picture-slides-selected-thumbnail");
                            $(thumbnailLinks[imageIndex]).addClass("picture-slides-selected-thumbnail");
                        }
                    },

                    // Navigate to previous image
                    prev = function () {
                        if (imageIndex > 0 || loopSlideshow) {
                            if (imageIndex === 0) {
                                imageIndex = (images.length -1);
                            }
                            else {
                                imageIndex = --imageIndex;
                            }
                            if (useFadingOut && (useFadeWhenNotSlideshow || slideshowPlaying) && imageIndex !== currentImageIndex) {
                                fadeContainer.stop();
                                fadeContainer.fadeTo(fadeTime, 0, function () {
                                    setImage(imageIndex);                                   
                                }); 
                            }
                            else {
                                if (useFadingIn && imageIndex !== currentImageIndex) {
                                    fadeContainer.css("opacity", "0");
                                }
                                setImage(imageIndex);
                            }
                        }
                    },

                    // Navigate to next image
                    next = function (specifiedIndex) {
                        if (imageIndex < (images.length -1) || typeof specifiedIndex !== "undefined" || loopSlideshow) {
                            if (typeof specifiedIndex !== "undefined") {
                                imageIndex = specifiedIndex;
                            }
                            else if (imageIndex === (images.length-1)) {
                                imageIndex = 0;
                            }
                            else {
                                imageIndex = ++imageIndex;
                            }
                            if (useFadingOut && (useFadeWhenNotSlideshow || slideshowPlaying) && imageIndex !== currentImageIndex) {
                                fadeContainer.stop();
                                fadeContainer.fadeTo(fadeTime, 0, function () {
                                    setImage(imageIndex);                                   
                                });
                            }
                            else {
                                if (useFadingIn && imageIndex !== currentImageIndex) {
                                    fadeContainer.css("opacity", "0");
                                }   
                                setImage(imageIndex);
                            }
                        }
                        else {
                            stopSlideshow();
                        }
                    },

                    // Start slideshow
                    startSlideshow = function () {
                        slideshowPlaying = true;
                        startSlideShowLink.hide();
                        stopSlideShowLink.show();
                        if (startSlideShowFromBeginning) {
                            next(0);
                        }
                        clearTimeout(timer);
                        timer = setTimeout(function () {
                            next();
                        }, timeForSlideInSlideshow);
                        if (useDimBackgroundForSlideshow && dimBackgroundOverlay[0]) {
                            elm.addClass("picture-slides-dimmed-background");
                            dimBackgroundOverlay.show();
                        }
                    },

                    // Stop slideshow
                    stopSlideshow = function () {
                        clearTimeout(timer);
                        slideshowPlaying = false;
                        startSlideShowLink.show();
                        stopSlideShowLink.hide();
                        if (useDimBackgroundForSlideshow && dimBackgroundOverlay[0]) {
                            elm.removeClass("picture-slides-dimmed-background");
                            dimBackgroundOverlay.hide();
                        }
                    };

                // Fade in/show image when it has loaded
                mainImage[0].onload = function () {
                    if (useFadingIn && (useFadeWhenNotSlideshow || slideshowPlaying)) {
                        fadeContainer.fadeTo(fadeTime, 1, function () {
                            if (slideshowPlaying) {
                                clearTimeout(timer);
                                timer = setTimeout(function () {
                                    next();
                                }, timeForSlideInSlideshow);
                            }
                        });
                    }
                    else {
                        fadeContainer.css("opacity", "1");
                        fadeContainer.show();
                        if (slideshowPlaying) {
                            clearTimeout(timer);
                            timer = setTimeout(function () {
                                next();
                            }, timeForSlideInSlideshow);
                        }
                    }
                    mainImageFailedToLoad.hide();
                };

                mainImage[0].onerror = function () {
                    fadeContainer.css("opacity", "1");
                    mainImageFailedToLoad.show();
                    if (slideshowPlaying) {
                        clearTimeout(timer);
                        timer = setTimeout(function () {
                            next();
                        }, timeForSlideInSlideshow);
                    }
                };

                // Previous image click
                previousLink.click(function (evt) {
                    prev();
                    return false;
                });

                // Next image click
                nextLink.click(function (evt) {
                    next();
                    return false;
                });

                // Start slideshow click
                startSlideShowLink.click(function () {
                    startSlideshow();
                    return false;
                });

                // Stop slideshow click
                stopSlideShowLink.click(function () {
                    stopSlideshow();
                    return false;
                });

                // Shows navigation links and image counter
                previousLink.show();
                nextLink.show();
                startSlideShowLink.show();
                imageCounter.show();

                // Stop slideshow click
                stopSlideShowLink.click(function () {
                    stopSlideshow();
                });

                // Thumbnail references
                if (thumbnailContainer[0]) {
                    thumbnailLinks = $(thumbnailContainer).find("a");
                    $(thumbnailLinks[imageIndex]).addClass("picture-slides-selected-thumbnail");
                    for (var i=0, il=thumbnailLinks.length, thumbnailLink; i<il; i++) {
                        thumbnailLink = $(thumbnailLinks[i]);
                        thumbnailLink.data("linkIndex", i);
                        thumbnailLink.bind(thumbnailEvent, function (evt) {
                            next($(this).data("linkIndex"));
                            this.blur();
                            return false;
                        });
                    }
                }

                // Sets initial image
                setImage();

                // If play slideshow at load
                if (startSlideshowAtLoad) {
                    startSlideshow();
                }

                if (dimBackgroundAtLoad) {
                    elm.addClass("picture-slides-dimmed-background");
                    dimBackgroundOverlay.show();
                }

                if (usePreloading) {
                    var imagePreLoadingContainer = $("<div />").appendTo(document.body).css("display", "none");
                    for (var j=0, jl=images.length, image; j<jl; j++) {
                        $('<img src="' + images[j].image + '" alt="" />').appendTo(imagePreLoadingContainer);
                    }
                }
            });
        };
    return {
        set : set,
        init : init
    };
}();
$(document).ready(function () {
    jQuery.PictureSlides.init();
});

【问题讨论】:

  • 请在您的问题中包含您的相关代码。
  • jquery on:api.jquery.com/on
  • 可能有一个脚本在元素更改之前将其副本保存为变量,因此您看到的是“旧源”。没有任何代码,但是任何人将呈现的任何东西都将在黑暗中拍摄。与生成插件的人交谈/发送电子邮件或在 IEchrome 中开始调试
  • 我给两位作者都发了邮件,没有回复。
  • 在更改 src 后,您可以尝试将插件重新应用到相关元素。

标签: javascript jquery dom


【解决方案1】:

创建一个您可以轻松调用的函数以应用经典的放大镜插件:

function addLoupe()
{
   $('.picture-slides-image').ClassyLoupe({
       maxSize: 600,
       size: 300,
       minSize: 200,
       loupeToggleSpeed: 'fast'
   });
}

然后在 jQuery.PictureSlides 文件中找到setImage 的部分,因为代码中的 cmets 表明这会设置主图像。在函数结束时,在关闭} 之前调用创建的函数addLoupe。这应该会重置新图像上的经典放大镜。

---- 编辑 挖掘 PictureSlides 代码,我看到有一个选项可以设置 thumbnailActivationEvent。当我跟随它到插件中设置/使用的位置时,我发现它被绑定的位置。如果您此时应用放大镜,新的大图像应该出现,并且您在picture-slides-image 上绑定了新类。

试试:

thumbnailLink.bind(thumbnailEvent, function (evt) {
   next($(this).data("linkIndex"));
   this.blur();
   addLoupe(); // reset your loupe settings here.
   return false;
});

如果这不起作用,我没有别的东西可以给你。

【讨论】:

  • 这看起来像相同的代码,但减去了 HTML 中的函数。但我把它放在你建议的地方,放大镜停止工作。
  • 所以您实际上在 PictureSlides 文件的 setImage 方法中调用了 addLoupe()?您是否在引入 PictureSlides 之前定义 addLoupe(这意味着您还需要在引入 PictureSlides 之前以及在定义 addLoupe 之前引入 ClassyLoupe?您是否在控制台中遇到任何错误?(在您的浏览器调出开发者工具)。
  • 根据您的指示,我在此处添加了 addLoupe():code// 设置主图像 setImage = function () { // 设置主图像值 var imageItem = images[imageIndex]; mainImage.attr({ src : imageItem.image, alt : imageItem.alt addLoupe() });code 不行。说语法错误。
  • 如果块// Adding/removing classes from thumbnail if (thumbnailContainer[0]) { thumbnailLinks.removeClass("picture-slides-selected-thumbnail"); $(thumbnailLinks[imageIndex]).addClass("picture-slides-selected-thumbnail"); } addLoupe(); },//end of add应该在此之后添加
  • 你不能在属性被编辑的地方添加函数调用。该函数是从setImage = function () { 开始到}, 结束的整个块。
猜你喜欢
  • 1970-01-01
  • 2017-07-11
  • 2014-03-18
  • 2021-09-05
  • 1970-01-01
  • 2010-09-12
  • 2015-05-08
  • 2020-01-14
  • 1970-01-01
相关资源
最近更新 更多