javascript - 如何将此脚本的设置保存在 cookie 中并使其依赖于另一个脚本?

标签 javascript jquery css cookies

我正在尝试制作一个按钮,以便在单击后切换网站背景。当然,设置需要保存在 cookie 中,以使其保持不变。

如何将这两个脚本结合起来,以便单击按钮后,它会保持切换状态,并带有背景?还是依赖于 body 类“点击”?

我找到了一种切换背景并将其保存在cookie中的方法:

$(document).ready(function() {
var body_class = $.cookie('body_class');
if(body_class) {
    $('body').attr('class', body_class);
}
$("#switch").click(function() {
    $("body").toggleClass('clicked');
    $.cookie('body_class', $('body').attr('class'));
});

});

然后按钮从 switch_on.png 切换到 switch_off.png:

$(function(){
$(".toggle-swap").click(function() {
if ($(this).attr("class") == "toggle-swap") {
  this.src = this.src.replace("switch_on.png","switch_off.png");
} else {
  this.src = this.src.replace("switch_off.png","switch_on.png");
}
$(this).toggleClass("on");
});

});

我的按钮:

<div id="switch"><a href="#"><img class="toggle-swap" src="../img/switch_on.png" alt=""></a></div>

最佳答案

我会将其合并为一个函数,例如像这样:

$(function() {
    // Create a variable for the current state
    var body_class;

    // Cache some elements
    var $body = $('body'), $switch = $('.toggle-swap');

    // Define a function that toggles background + button
    var toggleBodyClass = function(event) {
        // Toggle the images
        if (body_class) {
            $switch[0].src = $switch[0].src.replace("switch_off.png","switch_on.png");
            body_class = '';
        } else {
            $switch[0].src = $switch[0].src.replace("switch_on.png","switch_off.png");
            body_class = 'clicked';
        }

        // Toggle some css classes (body + button)
        $body.toggleClass('clicked');
        $switch.toggleClass('on');

        // Update the cookie
        $.cookie('body_class', body_class);

        // Prevent the browsers default behavior
        if (event) event.preventDefault();
    };

    // Set the initial state
    if ($.cookie('body_class')) {
        toggleBodyClass();
    }

    // Bind the event handler
    $switch.click(toggleBodyClass);
});

关于javascript - 如何将此脚本的设置保存在 cookie 中并使其依赖于另一个脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10781628/

相关文章:

javascript - SVG 图标只变形一次,不会变形回来

php - 如何根据单选类型选择切换 div?

jquery - 删除 HTML 中 Slider 和 Footer Div 之间的间隙

javascript - jQuery ui-日期选择器 : month and year dropdown css

javascript - Web Audio API 中 AudioWorkerNode 的状态

javascript - Laravel mix,如何为前端和管理部分设置不同的 css 和 js?

javascript - KnockoutJS 或 Javascript 未正确跟踪显示的数组

html - 显示器分辨率不同时按钮移动

css - 单击展开折叠交换背景

javascript - 使用 Javascript 验证日期输入