尝试通过 javascript 启用和禁用 css 文件

Trying to enable and disable css files through javascript

提问人:BigMoves 提问时间:9/13/2023 最后编辑:AlbinaBigMoves 更新时间:9/16/2023 访问量:52

问:

我有 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,无法弄清楚原因。试图与但不起作用。currentStyleSheetmobileLinkdesktopLink

在这里将不胜感激。谢谢!

javascript css dom 事件

评论

0赞 php_nub_qq 9/13/2023
显然没有与href“styles2.css”的链接
1赞 evolutionxbox 9/13/2023
您可以通过添加具有无效值的名为“media”的属性来禁用样式表。
1赞 GrafiCode 9/13/2023
在切换到移动设备时,您可以执行以下操作:但是该样式表不会再次添加到代码中任何位置的 DOM 中currentStyleSheet.remove();
1赞 CBroe 9/13/2023
将该属性设置为 true 也可用于使 -ed 样式表不适用。disabledlink
0赞 Teemu 9/13/2023
您目前拥有的是一次性代码。当您从 DOM 中删除样式表时,无法再使用 DOM 方法选择它。而是加载所有需要的样式表,并使用禁用属性来禁用不需要的样式表。

答:

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';
  }
});