我有几个用 PHP 生成的 CSS 文件。
我用点击事件改变了当前的 CSS 文件。
但它会在每次更改之间产生令人讨厌的白色闪光效果(仅在第一次加载它们时,下次它们在缓存中并且没有不良影响)。
如何通过点击事件预加载(但不显示)这个 CSS 文件?
$('.button').click(function(){
// Here I would like to preload the file
...
// Here I display it
$("#css").attr("href","css.php?id="+$(this).attr('id'));
});
编辑 > 解决方案
/* HTML File */
<link type="text/css" rel="stylesheet" href="css.php?id=1" id="css"/>
<link type="text/css" href="css.php?id=2" id="nextcss"/>
/* JS file */
$('.button').click(function(){
// Preload the file
$("#nextcss").attr("href","css.php?id="+$(this).attr('id'));
/* Here a lot of code with ajax...*/
// Here I display it
$("#css").attr("href","css.php?id="+$(this).attr('id'));
});
最佳答案
我假设这种“闪光效果”意味着,在加载 CSS 时,新规则正在逐步应用,但您希望同时应用所有规则。是对的吗?也许您可以将新创建的 css 元素附加到 dom(确保它将开始加载),但调整其属性,使其不会被解释为样式表(例如,不使用 rel="stylesheet"
)。加载完成后,您可以使用正确的值再次调整它,这应该会使整个更改立即出现。
另一个选项(尽管这需要更改您的 css)是创建一个类,以应用于 body
,并确保每个规则都引用 body.myclass
中的元素.当 css 完成加载时,将该类应用于正文。
关于javascript - 在显示文件之前,在 javascript 事件上预加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8958929/