开发者

Assign Class based on image width

I was curious if it was possible to look at an images width, and if the width is less than X number, then it would get a certain class.

Essentially I want to specify three classes for images like so:

  • If width is less than 100px then the image itself will have the class .small
  • If width is le开发者_JAVA技巧ss than 400px then the image itself will get the class .medium
  • If width is less than 600px then the image itself will get the class .large

.. etc If I need to add more sizes and classes

Is this possible?


var img = $("#myImage");
var width = img.width();
if (width < 100)
    img.addClass("small");
else if (width < 400)
    img.addClass("medium");
else if (width < 600)
    img.addClass("large");

Untested, but that looks about right.

Also, if you wanted to apply these rules to all images in your document, or at least all images in a specific container, you could:

$("#divWithImages img").each(function(i, el)
{
    var img = $(el);
    var width = img.width();
    if (width < 100)
        img.addClass("small");
    else if (width < 400)
        img.addClass("medium");
    else if (width < 600)
        img.addClass("large");
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜