【问题标题】:Dynamically Switching CSS Files动态切换 CSS 文件
【发布时间】:2016-12-28 04:30:38
【问题描述】:

尝试使用以下代码加载页面时收到两条错误消息。错误消息是:

  1. “未捕获的类型错误:无法在 HTMLAnchorElement.col.(匿名函数).onclick (http://www.jimbrink.org/:363:17) 处设置 null 的属性 'href'”
  2. “未捕获的 ReferenceError:bindEvents 未定义在(索引):375”

我正在尝试创建一个链接,当单击该链接时,它会切换到另一个 css 文件(使用不同的字体)。

(奖励问题:有没有办法让链接在两个样式表之间切换?)

我从另一个 StackOverflow 问题中得到了这个,但我似乎无法让代码在我的情况下工作。

这是链接:

                <li><a href="#" class="changeStyle" data-style="css/style.comicsans.css" data-type="text/css" data-rel="stylesheet">JB's Fav Font</a></li>

这是页面底部的js函数:

<!-- cssswitcher js -->
<script type='text/javascript'>
window.onload = function bindEvents(){

  var css=document.getElementById('style');
  var col=document.querySelectorAll('a.changeStyle');

  /* iterate through collection and assign listener */
  for( var n in col )if( col[n].nodeType==1 ) col[n].onclick=function(e){
    e.preventDefault();/* prevent jumping to top of page etc */
    var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;

    /* assign style attributes */
    css.href=el.dataset.style;
    css.rel=el.dataset.rel;
    css.type=el.dataset.type;

    /* store reference to style selected in localstorage */
    localStorage.setItem( 'style', el.dataset.style );
    };

  /* if there is a reference to the user's css choice in storage, assign it */
  if( localStorage.getItem( 'style' )!=null ) css.href=localStorage.getItem( 'style' );
  }

  document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>

【问题讨论】:

  • 问题的html 处没有元素将id 设置为"style"
  • 是的。但是css.style不应该从代码中定义的“el.dataset.style”设置吗?
  • console.log(css)console 跟在var css=document.getElementById('style'); 之后登录什么?您可以使用属性选择器选择元素。虽然当前 html 在 Question 不包含具有 id "style"? 的元素

标签: javascript jquery css


【解决方案1】:

首先,像这样定义原始样式:

HTML:

<link id="style" rel="stylesheet" type="text/css" href="style.css" />

注意我们将用来查找元素的id=style。这可能会解决您的第一个错误。

对于第二个,您必须决定是使用document.addEventListener( 'DOMContentLoaded', bindEvents, false ); 还是window.onload,因为它们是不同的功能。这可能会帮助你window.onload vs. body.onload vs. document.onready

所以,现在我们可以做一些 Javascript:

HTML(链接):

 <li><button onclick='setStyle("css/style.comicsans.css")'>JB's Fav Font</button></li>
 <li><button onclick='setStyle("css/style.other.css")'>Other Font</button></li>

首先,请注意,我只是在点击时使用一个参数来调用setStyle 函数,顺便说一句,最好使用&lt;button&gt;,这样我们可以获得更清晰的结果。

Javascript:

var cssStyle = document.getElementById('style');

window.onload = function(){
    if(localStorage && localStorage.getItem("style"))
        cssStyle.href = localStorage.getItem("style");
};

function setStyle(newStyle){
    cssStyle.href = newStyle;

    if(localStorage)
        localStorage.setItem("style", newStyle);
};

奖励: 但是,如果您只使用两种样式,请尝试简化,并使用速记方法来做到这一点:

HTML:

<li><button onclick='toggleStyle()'>Toggle</button></li>

<!-- cssswitcher js -->
<script type='text/javascript'>

    var cssStyle = document.getElementById('style');
    var listStyles = ["css/style.comicsans.css", "css/style.other.css"];

    window.onload = function(){
        if(localStorage && localStorage.getItem("style"))
            cssStyle.href = localStorage.getItem("style");
    };

    function toggleStyle(){
        var previousStyle = cssStyle.href;

        if(previousStyle.endsWith(listStyles[0]))
            newStyle = listStyles[1];
        else
            newStyle = listStyles[0];

        cssStyle.href = newStyle;

        if(localStorage)
            localStorage.setItem("style", newStyle);
    };
</script>

【讨论】:

【解决方案2】:

我在我的一个项目中使用 JQuery 做到了这一点,希望对您有所帮助:

HTML:

<ul id="projectList">
  <li class="project">Lorem Lorem</li>
  <li class="project viewed">Lorem Lorem</li>
  <li class="project viewed selected">Lorem Lorem</li>
  <li class="project viewed selected">Lorem Lorem</li>
  <li class="project viewed">Lorem Lorem</li>
</ul>

带有动态 CSS 代码的 JavaScript:

var data = {
  "projectColors": {
    "viewedColor": "#fffc20",
    "selectedColor": "#ff7920"
  }
};

var style = $(document.createElement("style")).attr("type", "text/css");
style.append("#projectList .project.viewed {color: " + data.projectColors.viewedColor + ";}");
style.append("#projectList .project.selected {color: " + data.projectColors.selectedColor + ";}");
style.appendTo("head");

JSFiddle:

https://jsfiddle.net/nikdtu/9gberp5o/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多