新的,更简单的答案
工作方式与以前类似,但增加了 2 个:1.) 如果最初没有类,则可以工作;2.) 如果其他函数在调用之间更改元素类,则可以工作。我还更改了函数名称,因此它不会干扰 jQuerys 本机 toggleClass。
$.fn.fancyToggleClass = function(new_class) {
return this.each(function() {
// get the last class this function added (if exists) or false (if not)
var $this = $(this),
toggled_class = $this.data('toggled-class') || false;
// if we dont have an original class, then set it based on current class
if (toggled_class) {
$this.removeClass(toggled_class);
}
// add new class and store as data,
// which we check for next time function is called
$this.addClass(new_class).data('toggled-class', new_class);
// alert the class, just as a check to make sure everything worked!
// remove this for production, or switch to console.log
alert('element class: ' + $this.attr('class'));
});
}
更新小提琴:http: //jsfiddle.net/facultymatt/xSvFC/3/
旧答案
我建议将原始类存储在元素数据属性中。然后,您的函数可以检查是否设置了此数据,如果是,则清除元素类,从元素数据中添加原始类以及您在函数中传递的新类。
如果未设置数据,该函数将在第一次运行时将当前类存储为数据。
查看此小提琴以获取带有注释的工作示例:http: //jsfiddle.net/facultymatt/xSvFC/
这是代码。这是一个 jquery 函数,因此可以在任何元素上调用它(并且也可以链接!)
$.fn.toggleClass = function(new_class) {
return this.each(function() {
// cache selector for this
$this = $(this);
// get original class (if exists) or false (if not)
var original_class = $this.data('original-class') || false;
// if we dont have an original class, then set it based on current class
if (!original_class) {
original_class = $this.attr('class');
$this.data('original-class', original_class);
// we do have an original class, so we know user is now trying to add class
// here we clear the class, add the original class, and add the new class
} else {
// assign the original class, and new class,
// and a space to keep the classes from becoming one
$this.attr('class', original_class + ' ' + new_class);
}
// alert the class, just as a check to make sure everything worked!
// remove this for production, or switch to console.log
alert('element class: ' + $this.attr('class'));
});
}
希望这可以帮助!