Let's say I have 4 imagedivs (imgdiv1, imgdiv2, imgdiv3, imgdiv4) and 4 contentdivs (condiv1 condiv2 condiv3, condiv4)and 1 main content div (maincon) all contentdivs (except the main content div) need to stay "hidden" or invisible. Each con will show up with a fadein effect when I do a mouseover on an imagediv. All contentdivs are in the same place while the imagedivs are a kind of menu.
Example: if I go with my mouse over imgdiv1, condiv1 will appear with a smooth fade in effect. When my mouse goes out of the imgdiv1, condiv1 should fade out to invisibility with a fadeout effect, same goes fo开发者_运维百科r imgdiv2, imgdiv3 and imgdiv4. the maincon div will always be there and the condivs should just go over the maincon when triggered with a mousover on imagedivs.
How can I achieve this using jQuery? What is the best way?
You could use the hover function
$('#imgdiv1').hover(function(){ /*fade in code*/},function(){/*fade out code*/});
alternatively you could look into JqueryUI and use the Tabs widget.
Have you looked at hover ? it combines mouse in / mouse out event handers, minimizing the code you need to write.
You would use hover() to toggle between two functions, one on mouseenter, the other on mouse leaving the imgdiv. For the sake of practicability, give an additional class to your imgdiv: "imgdiv". This allows you to create the behaviour once and attach it to all imgdiv elements , via an each(); loop.
Also, give a class "contentdiv" to all contentdiv elements so you can hide them via one single call.
$(document).ready(function(){
// hide all that should be hidden
$('div.contentdiv').hide();
var divToShow= '';
var strlength = 10;
$('div.imgdiv').each(function(){
$(this).hover(function(){
//find which contentdiv to show
var thisId= $(this).attr('id');
strlength = thisId.length;
divToShow = 'condiv'+thisId.charAt(strlength-1);
$(divtoShow).stop().fadeIn('slow');
}
,
function(){
// when mouse leaves imgdiv...
$(divtoShow).stop().fadeOut('slow');
}
);
});
});
精彩评论