提问人:BigMoves 提问时间:9/13/2023 最后编辑:AlbinaBigMoves 更新时间:9/16/2023 访问量:52
尝试通过 javascript 启用和禁用 css 文件
Trying to enable and disable css files through javascript
问:
我有 2 个不同的 css 文件,我想动态地使用它们。我有一个移动预览按钮,它将更改为另一个 css 文件,并将相同的按钮文本更改为桌面预览,我希望 css 更改为原始文件。我只能在按下移动预览时更改为第二个文件,但是在按下相同的按钮后,我收到错误"TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."
这是我的代码:
mobileBtn.addEventListener('click', () => {
const mobileLink = document.createElement('link');
mobileLink.rel = 'stylesheet';
mobileLink.type = 'text/css';
mobileLink.href = 'styles-no-media-query.css'
document.head.appendChild(mobileLink);
const currentStyleSheet = document.querySelector('link[href="styles2.css"]');
const alternativeStyleSheet = document.querySelector('link[href="styles-no-media-query.css"]');
if (currentStyleSheet) {
currentStyleSheet.remove();
document.head.appendChild(alternativeStyleSheet);
btnText.textContent = 'Desktop Preview';
} else {
alternativeStyleSheet.remove();
document.head.appendChild(currentStyleSheet);
btnText.textContent = 'Mobile Preview';
}
});
按下按钮后返回 null,无法弄清楚原因。试图与但不起作用。currentStyleSheet
mobileLink
desktopLink
在这里将不胜感激。谢谢!
答:
1赞
d.k
9/13/2023
#1
如果您尝试在单击处理程序中动态添加元素,我建议您尝试另一种方法。
只需有 1 个元素并在单击处理程序中更改其属性(主要是 href 属性,但您可能还需要更改其他属性)。
在文档中添加带有 .id='my-link-el'
然后,您将能够获取它并检查并更改其 href 属性(只要您定义了该变量并保持适当的值,该示例应该有效):btnTxt
mobileBtn.addEventListener('click', () => {
const linkEl = document.querySelector('#my-link-el');
const currentStyleSheetHref = 'styles2.css';
const alternativeStyleSheetHref = 'styles-no-media-query.css';
if (linkEl.href.endsWith(currentStyleSheetHref)) {
linkEl.href = alternativeStyleSheetHref;
btnText.textContent = 'Desktop Preview';
} else {
linkEl.href = currentStyleSheetHref;
btnText.textContent = 'Mobile Preview';
}
});
下一个:赋值后变量的值未更新
评论
currentStyleSheet.remove();
disabled
link