如何根据外观顺序更改多个图像的百分比宽度?

时间:2015-04-07 23:13:07

标签: javascript jquery css

假设页面上有三个9 *图像:

<img src="...">
<img src="...">
<img src="...">
<img src="...">
<img src="...">
<img src="...">
<img src="...">
<img src="...">
<img src="...">

*只是一个例子,不会总是有9个图像 - 可能是5或6等

如何使图像的百分比宽度对应于此顺序:

第1张图片:宽度:100%;

第二张图片:宽度:70%;

第3张图片:宽度:30%;

重复


与此处所做的类似:

总体而言,对于页面上的每个图像,宽度必须为:

第一张图片的100%,
第二张图片为70%,
第三张图片为30%,
对每个其他图像按此顺序重复,例如:
第四张图片为100%,
第五张图片为70%,
第六张图片为30%,

我相信脚本需要使用虽然我不知道该怎么做

基本实施:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    img:nth-of-type(3n+0) { width: 100%; }
    img:nth-of-type(3n+1) { width: 70%; }
    img:nth-of-type(3n+2) { width: 30%; }

    </style>
    </head>
    <body>

<div class="page">

    <div class="i">
    <img src="http://e794d552b4c822b8205c-27b9cc3fb8731a4a7598943b8a8a6a91.r73.cf1.rackcdn.com/1/1/large.jpg">
    </div>
    <div class="i">
    <img src="http://e794d552b4c822b8205c-27b9cc3fb8731a4a7598943b8a8a6a91.r73.cf1.rackcdn.com/1/1/large.jpg">
    </div>
    <div class="i">
    <img src="http://e794d552b4c822b8205c-27b9cc3fb8731a4a7598943b8a8a6a91.r73.cf1.rackcdn.com/1/1/large.jpg">
    </div>

</div>
    </body>
    </html>

3 个答案:

答案 0 :(得分:3)

一些奇特的CSS3选择器应该可以解决这个问题:

img:nth-of-type(3n+0) { width: 100%; }
img:nth-of-type(3n+1) { width: 70%; }
img:nth-of-type(3n+2) { width: 30%; }

请参阅the documentation for nth-of-type on MDN

请注意,这在IE8或更早版本中无效,您可能需要使用JavaScript解决方案。

答案 1 :(得分:0)

这会相应地设置页面中所有图片的宽度,因此请调整$("img")中的查询以仅匹配所需的图片。

var sizes = ["100%", "70%", "30%"];
$("img").each(function (idx, elem) {
  elem.width = sizes[idx % sizes.length];
});

答案 2 :(得分:0)

这可以在IE8中运行,但不太可维护且不太性感。这假设您的图像是元素内的唯一项目(例如,DIV):

img:first-child { width: 100%; }
img:first-child + img { width: 70%; }
img:first-child + img + img { width: 30%; }
img:first-child + img + img + img { width: 100%; }
img:first-child + img + img + img + img { width: 70%; }
img:first-child + img + img + img + img + img { width: 30%; }
img:first-child + img + img + img + img + img + img { width: 100%; }
img:first-child + img + img + img + img + img + img + img { width: 70%; }
img:first-child + img + img + img + img + img + img + img + img { width: 30%; }