【问题标题】:dynamically load css content from php file从 php 文件动态加载 css 内容
【发布时间】:2015-01-09 18:27:17
【问题描述】:

我有 css.php 文件,它将在每个 ajax 调用中动态生成样式,但如何在没有页面加载的情况下使用前端。 例如在 css.php ( .class1{color:#ddd;} .class2{color:#eee;} ) 中,它实际上是由 php 循环生成的,并通过键和值的组合创建类。 因此可以使用 ajax 或 jquery 从 php 加载 css 内容,如果是,那么如何?

【问题讨论】:

  • 是的,但这是一个加载的问题。您需要先了解使用 jQuery/Ajax 和 .CSS() 的基础知识,并针对您的场景尝试过一些示例。

标签: php jquery css ajax


【解决方案1】:

是的,这是可能的。您只需要:

  • 将此样式添加到您的页面 <head> 部分到 <style></style> 块中
  • 添加<link rel="stylesheet" type="text/css" href="css_script.php">

例如,第一个变体(使用 jQuery):

$.ajax({
    url: 'css_script.php',
    success: function(data) {
        $('#ajax-css').remove(); // Remove previous CSS
                                 // received by AJAX (if exists)

        var $styleElement = $('<style/>');
        $styleElement.attr('type', 'text/css');
        $styleElement.attr('id', 'ajax-css'); // ...so that we can find
                                              // and replace this element later
        $styleElement.html(data);
        $styleElement.appendTo($('head'));
    }
});

这是Fiddle.

【讨论】:

  • 实际上我使用的是 WordPress,所以在 href 中显示错误致命错误:调用未定义函数 get_option()
  • 在添加一些我自己的逻辑和你的部分逻辑之后,谢谢
猜你喜欢
  • 1970-01-01
  • 2020-10-07
  • 2015-10-12
  • 1970-01-01
  • 2020-05-30
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
相关资源
最近更新 更多