1

My target is to have a list of file names, and near every item a picture of that file extension will appear next to it.

there is a nice way to do that:

p[icon^=".gif"]
{
background: url(images/gif.png) no-repeat center left)
}

this checks if the icon attribute of the 'p' element ends with .gif. if it does, it applies the given style to that element.

but instead of define every file type, i want it to be generic since i have a folder with icons in this format: {file-extansion}.png

in case there is no matching file with the given extansion or there is no file extansion, there will be a default path of "default.png".

There is an option to do that or part of that? if no, what way you advise me doing that?

By the way I am not a css/javascript expert so please given enough details so I can understand your answers.

4

2 回答 2

1

You can use jQuery library for this:

HTML

<p data-ext=".gif">Text</p>
<p data-ext=".png">Text</p>
<p data-ext=".jpg">Text</p>

CSS

p {
    background-repeat: no-repeat;
    background-position: 0 50%;
}

JavaScript

$("p[data-ext]").each(function() {
    var ext = $(this).data("ext").substring(1);
    $(this).css("background-image", "url(images/" + ext + ".png)");
});

It works so that you add data-ext attribute to each p (or whatever) tag. jQuery selects all p tags which have data-ext attribute, then gets attribute value, and changes background-image of each element.

DEMO: http://jsfiddle.net/AEsx4/

于 2012-05-09T16:26:24.990 回答
1

Using pure CSS, you can't dynamically reference attributes in the URL, but you can make them content. Here are some lame workarounds using pure CSS and finally a wishful thinking approach :(

Use a class

<div class="jpg">
</div>


/* css */
.jpg {
   background: url("/img/jpg.jpg");
}

This works great, but you need one class per extension.

Use an attribute selector

<div data-ext="jpg"></div>

div[data-ext=jpg] {
   background: url(/img/jpg.jpg);
}

For more on this approach see: http://css-tricks.com/attribute-selectors/

I used data-ext, because in HTML you're not really supposed to add random tags, so the HTML creators gave us data-* which is valid HTML5 and we can do whatever want with it. Either way, you need to create a new CSS selector for every extension. Not good.

Closest you can get with pure css

<div data-ext="jpg"></div>

div:after {
   content: attr(data-ext);
}

You will see the name of the extension next to the div. This almost works, but it's not quite good enough.

More about CSS Functions: http://www.suburban-glory.com/blog?page=130

What you actually want

<div data-ext="jpg"></div>

div:after {
   content: url("/img/jpg." attr(data-ext));
}

Sadly this doesn't appear to work at the moment, but boy would it be awesome.

于 2012-05-09T17:48:22.500 回答