【发布时间】:2015-10-13 07:50:30
【问题描述】:
<div class="splash-image-wrap splash-image">
<img class="splash-image-bg" src="http://mysite-com/image.jpg" alt="image-bg">
</div>
您能帮我编写一个脚本,将 img src url 添加为 wrap div 的图像背景吗?
我正在尝试,但不起作用
$(function () {
function updatePageForTopImg(){
// background image using size cover
// top background image
$('.splash-image-wrap').css('background-image', 'url('+$(".splash-image-bg").attr("src")+')').css('background-size' , 'cover').css('background-position' , 'top center');
}
$(window).on('load', function(){
updatePageForTopImg();
});
});
【问题讨论】:
-
用纯 CSS 来做怎么样?正如我在您的代码中看到的那样,您的图像的 src 已经可用。如果您希望能够打开或关闭背景,您应该实现代表两种切换状态的 CSS 规则。通过 JS 应用大量 CSS 是一种不好的做法。
标签: javascript background-image