【问题标题】:Trying to toggle style CSS link "href" on click Jquery尝试在单击 Jquery 时切换样式 CSS 链接“href”
【发布时间】:2020-09-09 12:38:14
【问题描述】:

尝试在单击元素时进行暗模式切换

  1. 切换 div class= .dark__mode
  2. css 链接 class= .css 链接
  3. css 链接 href 变量 = style__old

我正在学习 jquery,我认为代码的推理和结构存在重大问题

链接href一开始会改变,但不会变回来

请帮忙,或者如果使用复选框选项更好

window.onload = function(){

    var  style__old = $(".css-link").attr("href");

    $(".dark__mode").click(function(){

            if (style__old == "css/style.css"){
                var style__new = style__old.replace("style.css","dark-mode.css");
                $(".css-link").attr("href", style__new);
            }
            else
            if (style__old == "css/dark-mode.css"){
                style__old.replace("dark-mode.css","style.css");
                $(".css-link").attr("href", "style__old");
            }
    }

);}

【问题讨论】:

    标签: jquery css toggle href


    【解决方案1】:

    您使用的动态更改加载的样式表的方法不是很可靠。

    更好的方法是将所有相关样式放入页面中,在单独的样式表中,然后 toggle() 一个低级元素上的类,例如 body,然后将所有选择器挂起。

    实际上它看起来像这样:

    jQuery($ => {
      $('.dark__mode').on('click', (e) => {
        e.preventDefault();
        $('body').toggleClass('dark');
      })
    });
    /* Normal layout */
    div { color: #0C0; }
    a { color: #C00; }
    
    /* Dark layout */
    body.dark {
      background-color: #333;
      color: #FFF;
    }
    body.dark div { color: #CCC; }
    body.dark a { color: #CC0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="#" class="dark__mode">Toggle</a>
    <div>
      <p>Lorem ipsum dolor sit</p>
      <a href="#">Amet consectetur adipcing elit</a>
    </div>

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 2013-09-09
      相关资源
      最近更新 更多