2017-09-14 41 views
-1

如何根据动态内容设置背景图片。根据动态内容设置背景图片?

html代码像下面

<div class="main-div"> 
    <div class="content-div"> 

    </div> 
</div> 
+0

你至今尝试过什么? –

+0

如何识别动态内容? – lpradhap

+0

如果我解释的是正确的,当你设置动态内容本身时,可能会使用.html()函数,你也可以使用.css()函数设置背景。 如果不是,您可以使用.html()获取内容并继续执行其余步骤 –

回答

1

$(document).ready(function() { 
 
    var imageUrl = 'https://www.stoneycreekhunting.co.nz/2_Key_Features_Rainwear_Insulation.png'; 
 

 
    $("<div class='dynamic-element'/>", { 
 
    text: "" 
 
    }).appendTo(".content-div"); 
 

 
    $('.dynamic-element').css({ 
 
    'background-image': 'url('+imageUrl+')', 
 
    'background-size': 'cover', 
 
    'height': '100%' 
 
    }); 
 
});
.content-div { 
 
    height: 100%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style="width:120px;height:120px;" class="main-div"> 
 
    <div class="content-div"> 
 

 
    </div> 
 
</div>

+0

我无法修复主div或内容div的高度宽度,因为内容div可能会自动填充大型文本内容或图像等 –

+0

https:///stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container – anu