Why is this Jquery code not working
I want to change the CSS of an input field over a time of 1800 milisec. It works, but there is no smooth transition. Do I have to put a fadeIn/Out somewher开发者_如何学Ce? What am I missing here:
$(".div-input").blur(function () {
$('.div-input').removeClass("div-input", 1800).addClass('div-input-second');
});
You can use .animate() to change the CSS values yourself, but there isn't a way to fade between classes like that.
Looks like invalid parameters for one, and also you can use contextual this
for the selector in your function
for blur
.
removeClass() takes either a class name or a function. Not sure what the 1800
in your parameter list. If you want animation look into animate.
Try this...
$(".div-input").blur(function () {
$(this).removeClass("div-input").addClass('div-input-second');
});
To do css style animations you need to use .animate jquery animate
To expand on previous answers, the .removeClass
and .addClass
functions don't have timing associated with them. You will need to animate the css manually if you want a class-to-class animation.
Here's an example:
CSS
.div-input{
color: red;
width: 200px;
}
.div-input-second{
color: blue;
width: 300px;
}
jQuery
$(".div-input").click(function () {
$(this).animate({
color: '#0000ff',
width: '300px'
}, 1800).removeClass("div-input").addClass('div-input-second');
});
This should cause the animation to occur, and then swap the classes after the animation finishes, so you can do more with that class name if you need to.
edit:
See this jsfiddle for a working demo using .click
. I'm not positive .blur
has a noticeable effect on div
elements.
edit 2:
A simple effect to fade an element out, swap classes and then fade it back in might look something like this (using the same css as above):
jQuery
$(".div-input").click(function () {
$(this).fadeOut(900, function(){
$(this).toggleClass("div-input div-input-second")
.fadeIn(1800);
})
});
You can see this in action at this updated jsfiddle.
Either use jQuery animate or have a look at this plugin, http://plugins.jquery.com/project/animate-to-class I've not tried it but seems to be what you're looking for.
Also - if you're using FireFox download Firebug - it has a good console for catching JS errors.
You can do it with JQuery UI http://jqueryui.com/demos/switchClass/
$(".div-input").blur(function () {
$(".div-input").switchClass("div-input", "div-input-second", 1800);
// Optionally to switch back
// $(".div-input-second").switchClass("div-input-second", "div-input", 1800);
});
As shown in this fiddle: http://jsfiddle.net/kSBP3/3/
精彩评论