【问题标题】:Add background image to a div via javascript通过javascript将背景图像添加到div
【发布时间】: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


【解决方案1】:

您希望在 css 文件中保留静态内容,例如背景大小和背景位置。

JS:

$('.splash-image-wrap').css({
    background-image: 'url(" + $('.splash-image-bg').attr('src') + ")'
});

CSS:

.splash-image-bg {
    background-size: cover;
    background-position: center top;
}

另外作为旁注,在您像 $(function(){}) 一样包装代码后,您的代码中不需要 window.loaddocument.ready

window.load 用于等待内帧和图像加载。由于您还没有注入背景图片,因此您无需等待它来运行您的代码。

另外,document.ready 相当于像 $(function() { 一样包装你的函数,你已经在这样做了。您可以完全废弃这些并让它仍然有效。

【讨论】:

  • 准确答案!删除了我的帖子;)没有意识到$前面的(function() {})+1
【解决方案2】:

假设您正在加载 jQuery 库,以下应该可以工作:

$('.splash-image-wrap').css({
    'background-image': 'url(" + $('.splash-image-bg').attr('src') + ")',
    'background-size': 'cover',
    'background-position': 'top center'
});

如果没有,您需要使用 vanilla JS 重写您的函数。

【讨论】:

    【解决方案3】:

    您有正确的代码,但不确定为什么您有$(window).load。 这是一个工作版本

    jsFiddle:https://jsfiddle.net/CanvasCode/rn7ejrke/1/

    jQuery

    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');
        }
    
    $(function () {
        updatePageForTopImg();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 2015-11-06
      相关资源
      最近更新 更多