简体   繁体   中英

Append data inside HTML5 picture srcset

Right now im doing what you see here:

$("#wrapper").prepend('<header> <picture> <source media="(max-width: 999px)" srcset="Images/Small/Primary-Logo.png", "Images/Small/2x/Primary-Logo.png 2x", "Images/Small/3x/Primary-Logo.png 3x"> <source media="(min-width: 1000px)" srcset="Images/Big/Primary-Logo.png", "Images/Big/2x/Primary-Logo.png 2x", "Images/Big/3x/Primary-Logo.png 3x"> <img src="" alt="Main Logo"> </picture> </header>')

My question is if there is a way to smartly insert data to each of those sources without having to prepend large chunks of text.

for example leaving all srcsets"" empty and adding the url by appending.

How do I do this?

So, first off, this:

srcset="Images/Small/Primary-Logo.png", "Images/Small/2x/Primary-Logo.png 2x", "Images/Small/3x/Primary-Logo.png 3x">

should be:

srcset="Images/Small/Primary-Logo.png, Images/Small/2x/Primary-Logo.png 2x, Images/Small/3x/Primary-Logo.png 3x">

Take a look at this for more info .

Here is a solution I can think of. See if this helps and also feel free to adapt this code to suit your needs.

var $wrapper = $("#wrapper");

var imageSrcs = {
    "tablet": ["Images/Small/Primary-Logo.png", "Images/Small/2x/Primary-Logo.png 2x", "Images/Small/3x/Primary-Logo.png 3x"],
    "desktop": ["Images/Big/Primary-Logo.png", "Images/Big/2x/Primary-Logo.png 2x", "Images/Big/3x/Primary-Logo.png 3x"]
};

$wrapper.prepend('<header> <picture> <source media="(max-width: 999px)" data-screen="tablet"> <source media="(min-width: 1000px)" data-screen="desktop"> <img src="" alt="Main Logo"> </picture> </header>')

$wrapper.find("[data-screen]").each(function() {

    var screenType = $(this).data("screen");
    $(this).attr({
        'srcset': imageSrcs[screenType].join(", ")
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM