2

我正在尝试制作一个按钮,一旦点击就可以切换网站背景。当然,设置需要保存在一个 cookie 中,才能坚持下去。

如何组合这两个脚本,以便单击按钮后,它与背景保持切换状态?还是依赖于身体类“点击”?

我找到了一种在 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>
4

1 回答 1

0

我会将它组合成一个函数,例如:

$(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);
});
于 2012-05-28T11:08:01.530 回答