簡體   English   中英

編寫此jQuery函數的更好方法?

[英]Better way to write this jQuery Function?

基本上,我正在嘗試精簡一些代碼,但是我不確定該怎么做,因為我有9個DIV都位於絕對位置。 它們都是灰色,但是當懸停時,懸停的DIV會淡出,而相應的DIV會淡入。是否有更好的書寫方式?

$('#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);
});

您可以為兩種類型的div添加兩個類。 例如:對於#l1到#l7,添加類“ .ln”; 對於#l1c到#l7c,添加類“ .lnc”,然后使用以下代碼:

$(".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);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM