2016-12-22 5 views
2

これは私のHTMLコードです:異なる画像に同じコードを適用する最も良い方法は? jqueryの

<div class="col-lg-2 vid"> 
     <img src="http://img.youtube.com/vi/hYj-XtJXGbs/maxresdefault.jpg" class="img-responsive " data-toggle="modal" data-target="#vid1"> 
     <p class="text">Text that comes over the image</p> 
</div> 

のjQueryコード:今すぐ

$('.vid').mouseenter(function() { 
    $('.text').css("visibility","visible"); 
}); 

、私は同じコードとクラスで別の画像を追加したい場合は何?明らかに私がこれを行うと、マウスが1つの画像上にある間に、両方の画像がオーバーレイ・テキストを表示します。

これは、すべてのイメージに異なるクラス/ IDを指定しない限り、これを行うにはどうしてですか?

答えて

4

thisキーワードを使用して、イベントを発生させた.vid要素を参照できます。 .textをスコープする必要がセレクタであるので、

$('.vid').mouseenter(function() { 
 
    $(this).find('.text').css("visibility", "visible"); 
 
});
.vid { 
 
    position: relative; 
 
} 
 
.vid p { 
 
    position: absolute; 
 
    width: 100%; 
 
    top: 10%; 
 
    visibility: hidden; 
 
    color: #C00; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="col-lg-2 vid"> 
 
    <img src="http://img.youtube.com/vi/hYj-XtJXGbs/maxresdefault.jpg" class="img-responsive " data-toggle="modal" data-target="#vid1"> 
 
    <p class="text">Text that comes over the image</p> 
 
</div>

+0

ありがとうございます!完全な作業 – user6527

4

はい:そこからは、このように、子.text要素を見つけるために、DOMをトラバースすることができます。代わりにこれを試してみてください:

$('.vid').mouseenter(function() { 
    $(this).find('.text').css("visibility","visible"); 
}); 

これが唯一の基礎となる.text要素に属性を追加します。

0

これは、複数のdivのお手伝いをすることができます:

$(function() { 
 

 
    $('.vid').on('mouseenter', function() { 
 
    $(this).find('.text').css("visibility","visible"); 
 
    }); 
 
    
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="col-lg-2 vid"> 
 
     <img src="http://img.youtube.com/vi/hYj-XtJXGbs/maxresdefault.jpg" class="img-responsive " data-toggle="modal" data-target="#vid1"> 
 
     <p class="text">Text that comes over the image</p> 
 
</div> 
 

 
<div class="col-lg-2 vid"> 
 
     <img src="http://img.youtube.com/vi/hYj-XtJXGbs/maxresdefault.jpg" class="img-responsive " data-toggle="modal" data-target="#vid2"> 
 
     <p class="text">Text that comes over the image</p> 
 
</div> 
 

 
<div class="col-lg-3 vid"> 
 
     <img src="http://img.youtube.com/vi/hYj-XtJXGbs/maxresdefault.jpg" class="img-responsive " data-toggle="modal" data-target="#vid1"> 
 
     <p class="text">Text that comes over the image</p> 
 
</div>

は、この情報がお役に立てば幸い!

+0

あなたの 'each()'ループは冗長です。 –

+0

あなたを取得できませんでしたか?それは魅力のように複数の 'div'のために働くことができます –

+0

' each() 'を使う必要は全くありません:' $( '.vid')。on( 'mouseenter'、fn) ' –

関連する問題