简体   繁体   English

使用jQuery或Javascript-定位图像,然后将其设置为div的背景图像

[英]Using jQuery or Javascript - target an image, then set it as a background image for a div

I had an idea today, and I was wondering if it was possible to do, and if I could get any pointers on how to accomplish it. 我今天有一个主意,我想知道是否有可能做到,是否能获得实现目标的任何指示。

I own an e commerce website that dynamically loads a product's image upon page load. 我拥有一个电子商务网站,可以在页面加载时动态加载产品的图像。 Here's the basic html structure for the image when it is loaded on the page: 这是图像在页面上加载时的基本html结构:

<div id="container">
<table>
<tr>
    <td>
        <a id="product_photo_zoom_url" herf="#">
            <img id="product_photo" />
        </a>
    </td>
</table>
</tr>
</div>

My idea is this: I would like to use a script to target the image #product_photo. 我的想法是这样的:我想使用脚本来定位图像#product_photo。 This script would then set that targeted image as a background image for the div #container. 然后,此脚本会将目标图像设置为div #container的背景图像。

I would then need to be able to set the following css for that dynamically added background image within the div #container in the script as well: 然后,我还需要能够在脚本的div #container中为动态添加的背景图像设置以下CSS:

#container {background-size: 100% auto; background-position: center top; opacity: 0.1;}

Hopefully that made sense. 希望这是有道理的。 Is this at all possible? 这是可能吗?

Thanks guys - Much appreciated. 谢谢大家-非常感谢。

var image = $("#product_phoro").attr('src');
$("#container").css('background-image', image);

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

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