Javascript 何时应用动态样式表?
我在javascript中动态加载了一些style.css。加载样式后,我将根据样式进行一些计算。代码如下所示:Javascript 何时应用动态样式表?,javascript,css,Javascript,Css,我在javascript中动态加载了一些style.css。加载样式后,我将根据样式进行一些计算。代码如下所示: link = document.createElement('link'); link.href = 'sheety.css'; link.rel = 'stylesheet'; document.head.appendChild(link); link.onload = function(){ //some code //here, I can't the the
link = document.createElement('link');
link.href = 'sheety.css';
link.rel = 'stylesheet';
document.head.appendChild(link);
link.onload = function(){
//some code
//here, I can't the the correct style sometime.
//but most of the time, I can get the correct style
setTimeout(function(){
//here, I can also get the correct style
}, 1000);
};
因此,我的问题是:该样式何时成功应用?如果我修改元素的位置(宽度、高度),我可以立即获得正确的值吗?或者我必须等待一段时间,让浏览器通过使用类似
setTimeout()的函数来执行操作
我读到一些参考资料说:calldom.getComputedStyle
将导致浏览器回流。
我确实调用了这个方法,但仍然得到了错误的DOM宽度/高度
当我在chrome中调试JS代码时,我可以看到在断点处没有应用样式(从chrome developer tools中的样式选项卡)。一旦加载样式表,就会生成CSSOM或。与DOM一起,CSSOM由光栅化器光栅化并应用(在Chrome中,由完成)
当浏览器完成回流或重新绘制时,可以说样式已成功应用。我们可以使用多种技术强制浏览器重新绘制:
元素。隐藏()。显示()#使用jQuery
将节点插入DOM
并将其移除
这些技术在一篇文章中得到了更好的解释