使用php创建css文件


create css file with php

我需要根据前端更改的变量创建一个可下载的css文件。

注:这是一个缩短的例子。

CSS:

.color: red; width: incrementvalue();

在html id中有一个inout字段来调整宽度,例如:

HTML

<input type="text" value="3">

然后Id有一个函数,它将在输入更改时运行,该函数将执行以下操作:

$('input').on ('change', function (){return $(this).val () * 2});

是的,上面的函数在jquery中,但我真的不知道php,我告诉我这应该在php中完成。

有什么想法吗?

您可以创建一个以CSS标头开头的常规PHP文件:

<?php
header('Content-type: text/css');

之后,您可以直接回显CSS内容。一种方法是使用带有模板系统的heredoc语法。该模板将变量值放在"%%"百分比符号中作为分隔符。这里有一个例子:

$css = <<<EOTAAA
* {
    margin: 0;
    padding: 0;
}
body {
    background-color: %bg_color%;
    background-image: url(images/bg.gif);
    background-repeat: repeat-x;
    font:  14px Arial, Helvetica, sans-serif;
}
div.my_div{
    color: red;
    width: %width%;
}
EOTAAA;
$search = array('%bg_color%', '%width%');
$width = width_function();//some function for determining width
$bg_color = bg_function();//some function for determining background color
$replace = array($bg_color, $width);
echo str_replace($search, $replace, $css);

下载链接:

在HTML中,创建一个类似这样的链接,其中包含将处理请求的文件的URL:

<a href="HTTP://www.example.com/download.php">Get CSS</a>

然后在PHP文件中,将头信息更改为以下内容:

header("Content-Disposition: attachment; filename='"custom.css'"");
header('Content-type: text/css');
header("Content-Type: application/force-download");
header("Connection: close");

试试这个,

<?php
   header("Content-type: text/css; charset: UTF-8");
   $my_width= incrementvalue();
?>
.phpClass{color: red; width: <?php echo $my_width;?>}

将此文件保存为style.php

用法

<link rel='stylesheet' type='text/css' href='style.php' />

读取http://css-tricks.com/css-variables-with-php/

我可以看到您正在绑定更改事件。这可能意味着您希望动态更改宽度。您不能在客户端使用PHP编写脚本。PHP是服务器语言,在这种情况下是无用的。如果您想动态地更改某些内容,则必须使用客户端脚本。jQuery(或Knockour.JS)可能是最简单的解决方案。

  1. 您最好使用javascript来增加输入框的宽度。使用PHP肯定会增加网络负载——每次更改输入框时,web浏览器都应该发送请求
  2. 如果您真的需要刷新样式表,<link id='dynamic_stylesheet' rel='stylesheet' type='text/css' href='style.php?length=3' />和稍后更改$('#dynamic_stylesheet')的href。在这种情况下,您最好只加载不同选择器的额外样式,然后再更改输入标记的类
  3. jQuery事件回调函数应该返回一个布尔值,表示它是否覆盖预定义的行为