简体   繁体   English

我该如何编写一个JS函数来在 <li> 类,并将该图像作为li的CSS中的背景图像值?

[英]How do I write a JS function that finds an img inside a <li> class and makes that image as a background-image value in the li's css?

To explain better. 解释得更好。 Imagine this: 想象一下:

<li class="whatever">
     <img src="/images/clients/something.jpg">
</li>
<li class="whatever">
     <img src="/images/clients/whatever.png">
</li>

Now, I want to write a JS function that will find the <img> tag in the <li> and will take the src value of the img and make it the background-image or the li class. 现在,我想编写一个JS函数,该函数将在<li>找到<img>标记,并采用img的src值并将其设置为背景图像或li类。 If there is a better way to do this, please let me know. 如果有更好的方法可以进行此操作,请告诉我。

This will help you: 这将帮助您:

var images = $('li > img');
images.each(function(){
    $(this).parent().css('background-image', 'url(' + $(this).attr('src') + ')');
    $(this).hide(); // to hide it
    $(this).remove(); // to remove it from the markup
});

Here's your jsfiddle: http://jsfiddle.net/R5PDJ/ 这是您的jsfiddle: http : //jsfiddle.net/R5PDJ/

You can also do: 您也可以:

$('li > img').each …

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM