【发布时间】:2013-04-21 17:48:28
【问题描述】:
背景图片有一些令人羡慕的 CSS 属性,我想将它们用于照片库——即 background-size: cover; 和 background-position: center center; 让您可以使用任何宽高比的图片,并将其与固定大小的容器完美匹配.
但是,我并不认为设置带有内容的背景图像是理想的。我宁愿在内容中使用<a href="url.jpg"><img src="url.jpg"/></a> 而不是<a href="url.jpg" style="background-image: url(url.jpg);"><img src="url.jpg"/></a>。我认为把前者写成后者的脚本是理想的。
给定的代码如下所示:
<a href="http://thesundaybe.st/media/from-earth-phone-23.jpg"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-24.jpg"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-26.jpg"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-27.jpg"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-28.jpg"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-29.jpg"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-30.jpg"></a>
我正在尝试编写一个 JQuery 脚本来获取 href URL 并将其设置为背景图像。基本上,把上面的代码变成这样:
<a href="http://thesundaybe.st/media/from-earth-phone-23.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-23.jpg);"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-24.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-24.jpg);"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-26.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-26.jpg);"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-27.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-27.jpg);"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-28.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-28.jpg);"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-29.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-29.jpg);"></a>
<a href="http://thesundaybe.st/media/from-earth-phone-30.jpg" style="background-image: url(http://thesundaybe.st/media/from-earth-phone-30.jpg);"></a>
这是一个带有基本 HTML/CSS 设置的 jsfiddle,只需要一点 JQuery:http://jsfiddle.net/MRSallee/tv3q8/3/
从理论上讲,这就是脚本发挥作用时的样子:http://jsfiddle.net/MRSallee/tv3q8/
我非常接近这一点 JQuery,但它似乎只是使用第一个 href 作为所有 <a> 标签的背景图像。
$('a').css({'background-image': 'url(' + $('a').attr('href') + ')'});
非常感谢任何帮助。干杯。
【问题讨论】: