简体   繁体   English

使用JS和PHP动态更新CSS文件源

[英]Dynamic updating CSS file source with JS and PHP

Is it possible to dynamicly change location of loaded CSS file? 是否可以动态更改已加载CSS文件的位置? For example: 例如:

        <?php 
            require_once "../objects/edit.php";
            $editor = new EDITOR_FACTORY($db);
        ?>
        <script>
            var type = "<?php $editor->call('Type') ?>";
            var theme = "<?php $editor->call('Theme') ?>";
            $('head').append('<link rel="stylesheet" href="../resources/styles/editor_templates/'+type+'_'+theme+'" type="text/css" />');
        </script>

Something like this? 像这样吗 I have some CSS file (templates) and I'd like to have an option change the theme without refreshing (change the CSS file source without refreshing page). 我有一些CSS文件(模板),我希望有一个选项可以更改主题而不刷新(更改CSS文件源而不刷新页面)。

The result should be something like 结果应该是这样的

<link rel="stylesheet" type="text/css" href="../resources/styles/editor_templates/sometype_sometheme.css

Right now it's returning blank variables "type" and "theme", they probably can't take data from the function from editor class (it's working in PHP but with refresh). 现在,它正在返回空白变量“ type”和“ theme”,它们可能无法从编辑器类的函数中获取数据(它在PHP中运行,但具有刷新功能)。 The thing is I am trying to delete last linked CSS file with JS and link the new one (but different, the one that user wanted, without refreshing page) 问题是我试图用JS删除最后一个链接的CSS文件并链接新的CSS文件(但不同的是,用户想要的那个文件,而没有刷新页面)
Thank you for any tips / suggestions! 感谢您的提示/建议!

The Answer is simple, you create a function and buttons with values (like this button will open CSS file 1, this CSS file 2 etc): 答案很简单,您可以创建一个函数和带有值的按钮(例如此按钮将打开CSS文件1,此CSS文件2等等):

<button class="loadCSS" value="1"> CSS file 1 </button>
<button class="loadCSS" value="2"> CSS file 2 </button>

and here is the magic: 这就是魔术:

var type = "<?php echo $editor->call('Type') ?>";
var theme = "<?php echo $editor->call('Theme') ?>";
$('head').append('<link id="'+ type+theme +'" rel="stylesheet" href="../resources/styles/editor_templates/'+type+'_'+theme+'.css" type="text/css" />');

$(document.body).on('click', '.loadCSS', function (e) {
   e.preventDefault();
   var buttonTheme = jQuery(this).val();
   $('#'+type+theme).remove(); 
   $('#'+type+buttonTheme).remove(); 
   $('head').append('<link id="'+ type+buttonTheme +'" rel="stylesheet" href="../resources/styles/editor_templates/'+type+'_'+buttonTheme+'.css" type="text/css" />'); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM