开发者

Storing images in custom data attributes

I have a h3 tag thats wrapping a img tag and the text. It works but I feel like its开发者_运维百科 a really bad idea to do. Example:

<h3> 
  <img src="dir/to/image.jpg" alt="icon" />
  Heading text
</h3>

I was reading about HTML5 custom data attributes (data-*) and then I remembered that I saw a tutorial on some website a while back ago that was using custom data attributes to store the icons and showing them beside the text (data-icon). This is exactly what I need.

Problem is I can't figure out how to output the image. How would I do this? Possibly with jQuery?


You use content: attr(data-icon) to output the image (other uses of the content property)


Are you talking about the data: URL scheme? The data scheme allows you to embed the image data right in the URL:

<img src="data:image/png;base64,iVBORw0KGg[bunch of base64 omitted]Jggg=="/>

Presumably you could store the data URL in a data-icon attribute and then copy it to src using jQuery when you need it:

<h3 data-icon="data:image/png:base64,...."><img/>Dot!</h3>

and then elsewhere:

$('h3').hover(
    function() {
        $(this).find('img:first').attr('src', $(this).attr('data-icon'));
    },
    function() {
        $(this).find('img:first').attr('src', '');
    }
 );

Of course you could add the <img/> tag in the jQuery stuff too but I'm trying to keep it simple for illustrative purposes.

AFAIK, browser support is okay for simple uses as long as you stay away from IE versions less than 8.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜