我在 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 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()
函数来做一些事情?
我读到一些资源说:调用 dom.getComputedStyle
会导致浏览器重排。
我确实调用了这个方法,但我仍然得到错误的 DOM 宽度/高度。
当我在 chrome 中调试 JS 代码时,我可以看到在断点处没有应用样式(从 chrome 开发人员工具中的样式选项卡)。
最佳答案
加载样式表后,CSSOM 或 CSSObjectModel生成。与 DOM 一起,CSSOM 由光栅化器光栅化并应用(在 Chrome 中,由 Skia 完成)。
当浏览器完成回流或重绘时,可以说样式应用成功。我们可以使用多种技术强制浏览器重绘:
- element.hide().show(); #使用 jQuery
- 向 DOM 中插入一个节点 并将其删除。
这些技术在 similar question 中有更好的解释。 .
关于javascript - 何时应用动态样式表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293803/