2016-04-15 16 views
2

少しCSS3のアニメーションで一般的なCSSバナーコードを使用しています(ポイントではなく、背景を提供しています)。私が達成しようとしているのは、カスタム属性を持つバナークラスを設定し、その属性コンテンツを取得し、jQueryを使用してスタイルを追加することです。これと同様に、しかし...同じページに同じ技術を使用することになりますこれらのdivの多く自分でカスタムattrを使用してCSSを追加しますか?

<div class="banner banner-small animate" data-bg="https://domain.com/path/img/bg.png"> 
    .... 
</div> 

次にjQueryの実行となり、出力コードなどが...

<div class="banner banner-small animate" data-bg="https://domain.com/path/img/bg.png" style="background-image: url('https://domain.com/path/img/bg.png')"> 
    .... 
</div> 

私はこれがあいまいではないことを願っています。私は最近jQueryの学習を始めました。私はそれを愛しています!これを行う方法については、実際には分かりません。

答えて

4

確かに、あなたはデータをセレクタとして属性を使用することができ、さまざまな方法があり、その後、data()機能を経由して自分のデータにアクセス:

// Iterate through each element with the data-bg attribute 
$('[data-bg]').each(function(){ 
    // Set the background image for each element to it's respective 
    // attribute value 
    $(this).css('background-image','url(' + $(this).data('bg') + ')'); 
}); 

それとも、二回のjQueryを起動したくない場合は、あなた

$('[data-bg]').each(function(){ 
    this.style.backgroundImage = url(' + this.getAttribute('data-bg') + ')'; 
}); 

または完全に明示的にループをforgoes adeneoから次のいずれか:

の提案を使用することができます210
$('[data-bg]').css('background-image', function() { 
    return 'url(' + $(this).data('bg') + ')'; 
}); 
+3

個人的なニックピット: 'this.style.backgroundImage = 'url(' + this.getAttribute( 'data-bg')+ ')';' jQueryを2回呼び出す代わりに) –

+0

ありがとう! –

+0

@NiettheDarkAbsol私もあなたのオプションを追加しました:) –

関連する問題