Tumblr: photoUrl-(size) - size depending on class?

二次信任 提交于 2019-12-13 01:26:42

问题


I have a Tumblr Site where the width of each post is determined by a tag.

If a post is tagged with #width200, the css class .width200 is assigned.

The problem is, though the posts have different widths, they all load the same size photo using the theme operator: {{PhotoURL-500}}.

This works, but for the smaller photos, it's a waste of bandwidth. I could use the theme operator {{PhotoUrl-250}} but this makes larger photos look bad.

Is there any way around this using theme operators or javascript?


回答1:


This creates the images on the fly, depending on the hashtag (use #s0, #s1, #s2 instead of #width200, it's easier)

This defaults to a 400px-wide image when Javascript is not available (and for bots like Google and Facebook)

{block:Posts}
    {block:Photo}
        <script id="{PostID}-image" data-images="{PhotoURL-250},{PhotoURL-400},{PhotoURL-500},{PhotoURL-HighRes}" data-classes="{TagsAsClasses}">
            (function () {
                //select current script tag
                var el = document.getElementById("{PostID}-image");

                //get data, this works in IE too
                var sizes = el.getAttribute('data-images').split(',');
                var classes = el.getAttribute('data-classes');

                //figure out which one is selected.
                //use hashtags like "#s1",
                //where 1 is the index of the url in data-images:
                //0 = 250, 1 = 400, 2 = 500, 3 = highres
                var imageIndex = classes.match(/\bs(\d)\b/);
                if (!imageIndex) {
                    imageIndex=[0,"0"];//no hashtag found, default to smallest image size
                }

                //create image and append it after the script tag
                var img = new Image();
                img.src = sizes[imageIndex[1]];
                el.parentNode.insertBefore(img, el.nextSibling);
            } ());
        </script>
        <noscript><img src="{PhotoURL-400}" alt=""></noscript>
    {/block:Photo}
{/block:Posts}

I haven't tested this, but you get the idea. If you find bugs, please edit/fix my answer.



来源:https://stackoverflow.com/questions/23751549/tumblr-photourl-size-size-depending-on-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!