是否可以动态更改加载的 CSS 文件的位置?例如:
<?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>
有这样的事吗?我有一些 CSS 文件(模板),我希望有一个选项可以更改主题而不刷新(更改 CSS 文件源而不刷新页面)。
结果应该类似于
<link rel="stylesheet" type="text/css" href="../resources/styles/editor_templates/sometype_sometheme.css
现在它返回空白变量“type”和“theme”,它们可能无法从编辑器类的函数中获取数据(它在 PHP 中工作,但有刷新)。问题是我试图用 JS 删除最后一个链接的 CSS 文件并链接新的文件(但不同,用户想要的文件,无需刷新页面)
感谢您的任何提示/建议!
最佳答案
答案很简单,您创建一个函数和带有值的按钮(例如此按钮将打开 CSS 文件 1、此 CSS 文件 2 等):
<button class="loadCSS" value="1"> CSS file 1 </button>
<button class="loadCSS" value="2"> CSS file 2 </button>
神奇之处在于:
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" />');
});
关于javascript - 使用 JS 和 PHP 动态更新 CSS 文件源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612787/