如何将动态图像作为CSS背景?

JRO*_*ROB 11 css php background

我有一个徽标div,我想用我的徽标图像作为背景,例如:

.logo {
    background: #FFF url(images/logo.jpg);
}
Run Code Online (Sandbox Code Playgroud)

但是,在我的脚本中的设置页面上,我希望有一个文本输入字段来指定图像URL对于背景图像的作用.

如何将此div的背景图像设置为输入的图像URL,而不必执行以下操作:

<div><img src="/images/logo.jpg" /></div>
Run Code Online (Sandbox Code Playgroud)

(该脚本是用PHP编写的)

Nat*_*han 31

以下是动态设置背景图像的两个选项.

  1. 将嵌入式样式表放在文档中<head>:

    <style type="text/css">
    .logo {
       background: #FFF url(<?php echo $variable_holding_img_url; ?>);
    }
    </style>
    
    Run Code Online (Sandbox Code Playgroud)
  2. background-image内联定义CSS属性:

    <div style="background-image: url(<?php echo $varable_holding_img_url; ?>);">...</div>
    
    Run Code Online (Sandbox Code Playgroud)

注意:确保在将输入保存到数据库之前清理输入(请参阅Bobby表).确保它不包含HTML或其他任何内容,只包含有效的URL字符,转义引号等.如果不这样做,攻击者可以将代码注入页面:

"> <script src="http://example.com/xss-attack.js"></script> <!--
Run Code Online (Sandbox Code Playgroud)


Cha*_*had 6

<input type="text" class="inputContent" />
<script type="text/javascript">
    var inputC = $('input.inputContent').val();
    $('body').css('background', 'url(' + inputC + ')');
</script>
Run Code Online (Sandbox Code Playgroud)

这完全是js和jQuery,因为我不懂PHP,但它是一个解决方案!