我正在使用 loadFileURL
加载本地内容的 WKWebView
中动态添加 2 个样式表。
cocoa 应用程序调用以下 javascript 片段来添加样式表。
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.title = csstype;
link.href = cssSheetPath1;
document.head.appendChild(link);
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.title = csstype;
link.href = cssSheetPath2;
document.head.appendChild(link);
这 2 个样式表位于同一目录中。我可以加载第一个或第二个,但不能同时加载。如果我尝试同时加载两者,则只会应用第一个。
知道问题出在哪里吗?
最佳答案
你必须运行两次。创建一个函数,然后为两个样式表调用它。
const createLink = (cssSheetPath) => {
const link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.href = cssSheetPath;
document.head.appendChild(link);
}
createLink('style1.css');
createLink('style2.css');
添加了一个运行代码示例:codesandbox example
如果你不使用一个函数,那么你应该尝试使用两个不同的变量名:
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.title = csstype;
link.href = cssSheetPath1;
document.head.appendChild(link);
var link1 = document.createElement('link');
link1.setAttribute('rel', 'stylesheet');
link1.type = 'text/css';
link1.title = csstype;
link1.href = cssSheetPath2;
document.head.appendChild(link1);
我无法使用 WKWebView 对其进行测试。
关于javascript - 仅在第一个时才考虑动态添加的样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315840/