How to have dynamic image as CSS background?

2020-05-20 02:07发布

I have a logo div that I want to use my logo image as the background for, such as:

.logo {
    background: #FFF url(images/logo.jpg);
}

However, on a settings page in my script, I would like to have a text input field to specify what the image URL is for the background image.

How can I set the background image for this div as the inputted image URL without having to do:

<div><img src="/images/logo.jpg" /></div>

(The script is written in PHP)

4条回答
Viruses.
2楼-- · 2020-05-20 02:34

Here are two options to dynamically set a background image.

  1. Put an embedded stylesheet in the document's <head>:

    <style type="text/css">
    .logo {
       background: #FFF url(<?php echo $variable_holding_img_url; ?>);
    }
    </style>
    
  2. Define the background-image CSS property inline:

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

Note: Make sure to sanitize your input, before saving it to the database (see Bobby Tables). Make sure it does not contain HTML or anything else, only valid URL characters, escape quotes, etc. If this isn't done, an attacker could inject code into the page:

"> <script src="http://example.com/xss-attack.js"></script> <!--
查看更多
家丑人穷心不美
3楼-- · 2020-05-20 02:37

I think you can set the background image dynamically using javascript as given here.

document.getElementById("xyz").style.backgroundImage="your path";

If you prefer not to use javascript, why can't you use inline style attribute.
ex

<div style="background-image: url(xyz)"></div>
查看更多
成全新的幸福
4楼-- · 2020-05-20 02:39
<input type="text" class="inputContent" />
<script type="text/javascript">
    var inputC = $('input.inputContent').val();
    $('body').css('background', 'url(' + inputC + ')');
</script>

That's entirely js and jQuery, because I don't know PHP, but it's a solution!

查看更多
手持菜刀,她持情操
5楼-- · 2020-05-20 02:52

You either need to generate the css from a PHP script (somewhat advanced), or use inline styles to do the trick. Ex:

<div style="background-image: <?php echo $_POST['whateverjpg']; ?>" >
//blah
</div>

This is incredibly insecure, but the most concise answer I can give..

查看更多
登录 后发表回答