Okay, so say I have a piece of text and I want to change its formatting by changing its class name. The class names are all organized in an array. (I'm not sure if this is the best way to go about it, so I'm more than happy to take suggestions to the contrary)

So say the class name was class1 and I had the array

[class1, class2, class3, ..., class10]

What's the best way to cycle the class name to the next item in the array on a mouseover using jQuery?

有帮助吗?

解决方案

Here is an alternative that doesn't use a counter.

http://jsfiddle.net/mqchen/9LHE5/

var classes = ["red", "blue", "green", "papayawhip"];

$("#something").mouseenter(function(e) {
    classes.push(classes.shift());
    $(this).removeClass(classes[classes.length - 1]).addClass(classes[0]);
});​

Basically, it removes the first element from the array, using shift, appends it to the end of the array, then removes that class (which is now at the end of the array) from the element, and then adds the first element from the array (which used to be the second element), using push.

EDIT: Here is a revision that starts on the first class in the array instead of the second. http://jsfiddle.net/mqchen/9LHE5/2/

其他提示

Store a global counter, and use it by counter % classes.length where classes is your array. It just keeps incrementing but % returns the correct index when used with the length of your array classes.length.

​var classes = ['class1','class2','class3','class4'];
// Will hold the current iteration's index
// initialized to 0 on page load...
var counter = 0;

function advance() {
  // Remove the current iteration's class based on the counter's current value
  $('#thediv').removeClass(classes[counter] % classes.length);

  // Increment the counter to the next value
  counter++;

  // Add the new iteration's class based on the counter's *new* incremented value
  $('#thediv').addClass(classes[counter % classes.length]);
}​​​​​​​​​​​​​​​
​

Bind the advance() function to your node's onmouseover.

$(document).ready(function() {
  $('#yourElement').mouseover(advance);
});​

Here is a demo on jsfiddle.net

jsBin demo

Let's say your class is called .font + and an N number:

CSS:

h1{
  color:purple;
}

.font0{
 color:gray !important;
}

.font1{
 color:red !important;
}

.font2{
 color:blue !important;
}

.font3{
 color:gold !important;
}

jQuery:

var c = 0;
$('h1').on('mouseenter',function(){  
  $(this).removeClass().addClass( 'font'+ (c++%4) ); 
  // console.log( c%4 ); // TEST counter
}); 

is good to use the !important if you plan to ADD / overwrite some element existent styles.

You need to remove from the element the CLASS before adding a new one using .removeClass().

var classArr = ['class-1', 'class-2', 'class-3', ...],
    classArrLengthNum = classArr.length,
    arrIdxNum = 0;

$(el).mouseover(function () {
    arrIdxNum += 1;
    if (arrIdxNum === classArrLengthNum) {
        arrIdxNum = 0;
    }

     el.attr('class', classArr[arrIdxNum]);
});

Something like this should work:

$('#theelement').mouseover(function(e) {
    var classes = ['class1', 'class2', 'class3', 'class10'],
        $this = $(this),
        current = $this.attr('class').split(' ');
    for (var i = 0; i < current.length; i++) {
        lindx = $.inArray(current[i], classes);
        if (lindx != -1) {
            classname = current[i];
            next = lindx + 1 >= classes.length ? classes[0] : classes[lindx + 1];
            $this.toggleClass(classname + ' ' + next);
            break;
        }
    }
});

http://jsfiddle.net/szh7K/

Ive done it this way instead of using a counter so that there is no need for an external variable. PRobably a better implementation would be to use a counter instead of searching the array everytime but use $.data to store that counter index on the element itself.

$('#theelement').mouseover(function(e) {
    var classes = ['class1', 'class2', 'class3', 'class10'],
        $this = $(this),
        cur = $this.data('currentIndex')||0, // if there is no value then we start from scratch
        next = cur+1 >= classes.length ? 0 : cur+1; // if we are at the end we start over

        $this.toggleClass(classes[cur] + ' ' + classes[next]); // toggle the classes
        $this.data('currentIndex', next); // assign the incremented index as current
});

http://jsfiddle.net/jkPps/1/

Start by declaring your classes, and a variable to track the current index:

var classes = ["red", "blu", "grn"], index = -1;

Next setup the mouseenter functionality:

$("body").on("mouseenter", function(){
    this.className = classes[++index % classes.length];
});​​​

This will grab the next available value from the array, and when it's at the end of the array it will wrap back around and grab the item at index 0.

Demo: http://jsfiddle.net/R48FC/

This version preservers any other classes that might have been set on the element you are cycling the classes on. It also passes jsLint ;-)

$.ready(function () {
    'use strict';
    var cycles = ['class1', 'class2', 'class3', 'class4'],
        cycleLength = cycles.length,
        cycleCount = 0; // assumes the first class was already set in the HTML

    $('#element').mouseover(function (ev) {
        var $this = $(this);
        // remove the previous class
        $this.removeClass(cycles[cycleCount]);

        // get the next class
        cycleCount += 1;
        cycleCount %= cycleLength;

        // add new class
        $this.addClass(cycles[cycleCount]);
    });
});

You'll notice that in this working example the text stays bold since the .b class is not removed when it cycles through the classes from the array. You might also want to use jQuery.mouseenter() instead of mouseover if the element you are putting this event on has child nodes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top