【问题标题】:Prepend custom css to generated CSS files在生成的 CSS 文件中添加自定义 CSS
【发布时间】:2014-11-18 07:18:35
【问题描述】:
这是我的问题:
我正在使用 WordPress,我有简单的按钮短代码。
用户可以为他们创建的每个按钮选择一种颜色,也可以在按钮悬停时选择一种颜色。
我为每个按钮生成了自定义 css <style> 标签,它工作正常,但只有一个问题,它在页面和使用 IE9 时创建了很多 <style> 标签(限制为 31)按钮样式不适用。
css 是用我的简码函数用 php 生成的。
我正在寻找一种将 css 生成为动态 css 文件的方法。
如果将所有 <style> 放入一个 css 文件中,它应该可以与 IE 一起使用,但我不知道该怎么做。
任何帮助将不胜感激。
【问题讨论】:
标签:
php
html
css
internet-explorer
stylesheet
【解决方案1】:
你可以用 jQuery 解决它:
function isIE() {
return (navigator.userAgent.toLowerCase().indexOf('msie ') != -1) || (!!navigator.userAgent.match(/Trident.*rv[:]*11\./));
}
$(function() {
if (isIE()) {
//merging all the content in your generated styles
var styles = $("style").text();
//getting rid of the many unneeded styles
$("style").remove();
//Putting back all the styles into your document
$("head").append("<style>" + styles + "</style>");
}
});
这个想法是将样式合并到一个文本中,删除所有样式,然后创建一个样式标签来代替它们。您只需要 IE,所以我添加了一个功能,您可以使用该功能检查它是否是 Internet Explorer,如果是,则合并样式。
【解决方案2】:
假设这些是动态生成的,最简单的解决方案是在页面头部生成一个自定义样式部分。您需要在此部分之前包含您的主要 CSS 文件才能覆盖值。
【解决方案3】:
如果你也喜欢,你可以使用 'fopen()' 将所有自定义 css 发送到一个新文件:
function CreateCustomCSSFile(){
$file = fopen("wp-content/themes/your_theme/css/your_stylesheet_custom_file.css","w"); // change the target path as you like
$Color1 = '#eee'; // your custom color 1 - replace the Hex value with the custom field input
$Color2 = '#000'; // your custom color 2 - replace the Hex value with the custom field input
// getting the custom values into css
$TheCSSLayout = '
.someclass1
{
background: ' . $Color1 . ';
}
.someclass2
{
background: ' . $Color2 . ';
}
';
fwrite($file, $TheCSSLayout); // writing to the file
fclose($file); // closing the file
}
CreateCustomCSSFile();
将其插入到function.php文件中,并将新文件调用到头部的css包含文件的末尾,这样它将覆盖默认的css设置。