gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:41:40 24 4
gpt4 key购买 nike

我正在尝试制作一个按钮,以便在单击后切换网站背景。当然,设置需要保存在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com