用Javascript在单击时切换CSS样式表。

8

尝试使用一个按钮来切换两个样式表的代码。我已经尝试了适应他人的解决方案,但至今未果。以下是我最近的尝试:

设置:

<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<script type="text/javascript">
function toggle() {
    var el = document.getElementById("style1");
    if (el.href == "resumecss.css") {
        el.href = "resumecssinvert.css";    
    }
    else {
        el.href = "resumecss.css";  
    }
}
</script>

调用:

<button type="button" onclick="toggle()">Switch</button>

目的是在同一个页面上反复切换两个样式。

感谢那些愿意帮忙的善良/有知识的人。

6个回答

8
尝试同时包含它们,然后切换禁用标志。
<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<link id="style2" rel="stylesheet" type="text/css" href="resumecssinvert.css" disabled="disabled" />
<script type="text/javascript">
  function toggle() {
    var el1 = document.getElementById("style1"),
        el2 = document.getElementById("style2");
    if (el1.disabled === "disabled") {
      el1.disabled = undefined;
      el2.disabled = "disabled";
    } else {
      el1.disabled = "disabled";
      el2.disabled = undefined;
    }
  }
</script>

使用属性方法更新示例:

const
  normalStyle   = document.getElementById('style1'),
  invertedStyle = document.getElementById('style2');

const toggle = (style1, style2) => {
  if (style1.hasAttribute('disabled')) {
    style1.removeAttribute('disabled');
    style2.setAttribute('disabled', '');
  } else {
    style1.setAttribute('disabled', '');
    style2.removeAttribute('disabled');
  }
}

toggle(normalStyle, invertedStyle); // Swap disabled flag
<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<link id="style2" rel="stylesheet" type="text/css" href="resumecssinvert.css" disabled />


我不确定浏览器缓存是如何工作的,但这种方法可能会使用户体验更加流畅,因为它只在最开始加载两个规则集一次。 - Symbolic

5
你的脚本很好,只是`href`属性是完整的URL,即使你使用了相对路径。这是我用的代码,它可以工作:
function toggle() {
    var el = document.getElementById("style1");
    if (el.href.match("resumecss.css")) {
        el.href = "resumecssinvert.css";    
    }
    else {
        el.href = "resumecss.css";  
    }
}

在这里查看演示: http://jsfiddle.net/jakelauer/LWJjX/

+1,但下次请将JavaScript与HTML分开:http://jsfiddle.net/LWJjX/3/ - Broxzier

5

这是我能想到的最简短的解决方案(并且可能适用于所有浏览器):

function toggle() {
  var a = document.getElementById("style1");
  a.x = 'resumecssinvert' == a.x ? 'resumecss' : 'resumecssinvert'; // short if
  a.href = a.x + '.css';
}

作为javascript中的一切都是对象,因此您可以简单地添加属性。
假设您的默认CSS是“ resumecss”。
第一次x未设置并返回false,因此将设置“ resumecssinvert”。
第二次x设置并返回true并切换回来。 一切正常运作。

只有一次有效,当我再次点击按钮时,它就停止工作了。 - K.K Designs

1
将两个样式表添加到页面中,单击按钮禁用其中一个,另一个会自动激活。
let button = document.getElementById("IdName")
button.addEventListener("click", () => {
  let stylesheet = document.getElementById("style1");
  stylesheet.toggleAttribute("disabled")
})

0

这个可以用jQuery来实现。

$('#dark-css').click(function() {
  var $darkCss = $("link[href='dark.css']");
  if ($darkCss.length) {
    $darkCss.remove();
  } else {
    $('head').append('<link type="text/css" rel="stylesheet" media="all" href="dark.css">');
  }
});

更新的示例

(function($) {
  $.createStylesheet = function(href) {
    return $('<link>', {
      type: 'text/css',
      rel: 'stylesheet',
      media: 'all',
      href: href
    })
  };
})(jQuery);

$('#dark-css').click(function() {
  var $darkCss = $('link[href="dark.css"]');
  if ($darkCss.length) {
    $darkCss.remove();
    console.log('Removing dark theme...');
  } else {
    $('head').append($.createStylesheet('dark.css'));
    console.log('Loading dark theme...');
  }
});
.as-console-wrapper { max-height: 3rem !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" media="all" href="dark.css">
<h1>Hello World</h1>
<button type="button" id="dark-css">Toggle Dark Mode</button>


0
在下面的答案中,样式表可以被预先添加或延迟加载。它们通过其href属性值在文档中定位。
它们可以被预先加载或按需加载。一旦它们被加载,可以通过切换它们的disabled属性来启用/禁用它们。这样,脚本只会被加载一次。

const main = () => {
  const
    normalStyle   = getOrLoadStylesheet('resume.css'),
    invertedStyle = getOrLoadStylesheet('resume-inverted.css');

  toggleStylesheet(normalStyle, invertedStyle); // Swap disabled flag
};

const createElement = (tagName, config, target) => {
  const el = Object.assign(document.createElement(tagName), config);
  if (target) target.append(el);
  return el;
};

const createStylesheet = (href) =>
  createElement('link',
    { rel: 'stylesheet', type: 'text/css', disabled: 'disabled', href },
    document.head);

const getOrLoadStylesheet = (href) =>
  document.querySelector(`link[href="${href}"]`) ?? createStylesheet(href);

const toggleStylesheet = (style1, style2) => {
  if (style1.hasAttribute('disabled')) {
    style1.removeAttribute('disabled');
    style2.setAttribute('disabled', '');
  } else {
    style1.setAttribute('disabled', '');
    style2.removeAttribute('disabled');
  }
}

main();
<!--

<link rel="stylesheet" type="text/css" href="resume.css" />
<link rel="stylesheet" type="text/css" href="resume-inverted.css" disabled />

-->


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接