2016-04-26 13 views
0

こんにちは私はこれらの4つの同様の機能を簡素化したいと思います。最終的にセレクタのみが変更されます。どうすればいいですか?多くのありとあらゆること!複数の代わりに単一の関数を使用するJQuery

$('.box.standard .title').css({ 
       'position' : 'absolute', 
       'left' : '50%', 
       'top' : '50%', 
       'margin-left' : -$('.box.standard .title').outerWidth()/2, 
       'margin-top' : -$('.box.standard .title').outerHeight()/2 
      }); 

      $('.box.large .title').css({ 
       'position' : 'absolute', 
       'left' : '50%', 
       'top' : '50%', 
       'margin-left' : -$('.box.large .title').outerWidth()/2, 
       'margin-top' : -$('.box.large .title').outerHeight()/2 
      }); 

      $('.box.wide .title').css({ 
       'position' : 'absolute', 
       'left' : '50%', 
       'top' : '50%', 
       'margin-left' : -$('.box.wide .title').outerWidth()/2, 
       'margin-top' : -$('.box.wide .title').outerHeight()/2 
      }); 

答えて

0

試してみてください。

var myArray = ['.box.standard', '.box.large', '.box.wide']; 

for (var i of myArray) { 

    $(i+' .title').css({ 
       'position' : 'absolute', 
       'left' : '50%', 
       'top' : '50%', 
       'margin-left' : -$(i+' .title').outerWidth()/2, 
       'margin-top' : -$(i+' .title').outerHeight()/2 
      }); 

} 
+0

ありがとう、それは完璧に動作します! – Titifrim

1

が機能してください、あなたが好きなときにそれを使用する:

function myFunction(cssClasses){ 

    $(cssClasses).css({ 
        'position' : 'absolute', 
        'left' : '50%', 
        'top' : '50%', 
        'margin-left' : -$('.box.wide .title').outerWidth()/2, 
        'margin-top' : -$('.box.wide .title').outerHeight()/2 
       }); 

} 

myFunction('.box.standard .title'); 
myFunction('.box.large .title'); 
myFunction('.box.wide .title'); 
0

あなたが選択を指している、あなたはthisへのアクセスを支援する機能を使用することができます素子。これでいいはずです:

 $('.box.standard .title, .box.large .title, .box.wide .title').css({ 
      'position' : 'absolute', 
      'left' : '50%', 
      'top' : '50%', 
      'margin-left' : function() { 
       return -$(this).outerWidth()/2; 
      }, 
      'margin-top' : function() { 
       return -$(this).outerHeight()/2; 
      } 
     }); 
関連する問題