如果条件为真,如何在重新调整大小时仅更改一次图像的 src,而不是每次重新调整窗口大小时?



我当前正在创建一个函数以获取图像的src,然后将SRC更改为较小的移动友好映像。

我正在尝试使其尽可能动态和灵活,但现在我只在一个图像上测试。

问题是在重新尺寸的小提琴时,它将继续将文本字符串添加到最终破坏它的SRC中。(正则表达式也不会在绝对路径上发挥作用,因此我不会期望图像可以正常工作。)

路径应为:

<img src="http://chatfielddrilling.com/Chatfield%20V2/images/home-slide-1-mbl.jpg" alt="overview of building" />

,但是,如果正则不更换一切,它看起来像:

<img src="http://chatfielddrilling.com/Chatfield%20V2/images/home-slide-1-mbl-mbl-mbl-mbl-mbl.jpg" alt="overview of building" />

它只会一遍又一遍地添加-mbl,直到重新尺寸停止为止,负载函数似乎不起作用。(也许我无法将$(window)瞄准负载,我仍然是脚本的新手)

我试图通过将-mbl添加到每个图像的ALT的末端来减少移动加载时间,但我不知道如何停止此功能来使此灵活。

这是我目前的jQuery:

var orgSrc = $('img').attr('src');
$(window).on('load resize', function() { // Resize/load function to change images for mobile phones
    var imgSrc = $('img').attr('src'), // Snags the img's src
        imgPaths = [ 'jpg', 'png', 'gif', 'svg' ], // Array of image types
        mobileImg = imgSrc.match(/[^.]+/) + '-mbl.' + imgPaths[0]; // Dynamically makes the new src for mobile sites
    if ($(window).width() < '800') {
        $('img').attr('src', mobileImg); // If is true then replace with new url
    }
    else {
        $('img').attr('src', orgSrc); // If is not true then replace with old
    }
});

最后,小提琴:演示

我也可能正在使用正则正则是错误的,这是我第一次尝试使用它,所以如果我犯了一个新手错误,我深表歉意。

您可以为实际调整大小时指定一个true/false标志。这些行:

var orgSrc = $('img').attr('src');
$(window).on('load resize', function() { // Resize/load function to change images for mobile phones
    var imgSrc = $('img').attr('src'), // Snags the img's src
        imgPaths = [ 'jpg', 'png', 'gif', 'svg' ], // Array of image types
        mobileImg = imgSrc.match(/[^.]+/) + '-mbl.' + imgPaths[0], // Dynamically makes the new src for mobile sites
        hasResized = false;
    if(!hasResized) {
        if ($(window).width() < '800') {
            $('img').attr('src', mobileImg); // If is true then replace with new url
            hasResized = true;
        }
        else {
            $('img').attr('src', orgSrc); // If is not true then replace with old
        }
    }    
});

这将使您的属性仅更改一次,然后您将其锁定在此更改中。如果您需要再次进行检查,您可能必须获得更多的创意。

希望这会有所帮助!

最新更新