简体   繁体   中英

Better way to write this jQuery Function?

basically I am trying to trim down some of this code, but I am not sure how to do so, I have 9 DIV's positioned all absolute in different spots. They are all Grey, but when hovered the DIV that is hovered, fades out and the corresponding DIV fades in. Is there a better way to write this?

$('#l1').hover(function () {
    $(this).fadeOut('300');
    $('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
    $(this).fadeOut('300');
    $('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
    $(this).fadeOut('300');
    $('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
    $(this).fadeOut('300');
    $('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
    $(this).fadeOut('300');
    $('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
    $(this).fadeOut('300');
    $('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l7').fadeIn('300')
});
$('#l1,#l2,#l3,#l4,#l5,#l6,#l7').hover(function() {
    $(this).fadeOut(300);
    $("#" + this.id + "c").fadeIn(300);
});

$('#l1c,#l2c,#l3c,#l4c,#l5c,#l6c,#l7c').mouseout(function() {
    $(this).fadeOut(300);
    $("#" + this.id.substring(0, this.id.length - 1)).fadeIn(300);
});

You can add two class for the two types of div. eg: for #l1 to #l7, add class ".ln"; for #l1c to #l7c, add class ".lnc", then use below code:

$(".ln").live("hover", function(){
  $(this).fadeOut('300');
  $("#" + $(this).attr("id") + "c").fadeIn(300);
};

$(".lnc").live("mouseout", function(){
  var id = $(this).attr("id");
  $(this).fadeOut('300');
  $("#" + id.substring(0, id.length - 1)).fadeIn(300);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM