如何将动态图像作为CSS背景? [英] How to have dynamic image as CSS background?

查看:352
本文介绍了如何将动态图像作为CSS背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

但是,在脚本的设置页面上,我想要一个文本输入字段来指定背景图像的图像URL.

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.

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

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>

(脚本是用PHP编写的)

(The script is written in PHP)

推荐答案

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

Here are two options to dynamically set a background image.

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

  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>

  • 内联定义background-image CSS属性:

  • Define the background-image CSS property inline:

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

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

    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> <!--
    

    这篇关于如何将动态图像作为CSS背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆