2016-06-15 10 views
0
**CSS** 

    #child:focus > #parent { 
    color: white; 
    } 

    **HTML** 
    <div id="parent"> 
     <div id="child"> 
     </div> 
    </div> 

これは、子がフォーカスされているときに親にスタイルを適用する正しい方法ですか?親要素がフォーカスされているときに親要素のスタイルを適用する

編集:私の問題は、これらのスタイルを小さなデバイスに適用する必要があることです。だから私はJqueryを使用することはできません。それは私がCSSでメディアクエリ内で試している理由です。

ます。また、このためにjQueryを使用することができます
+0

問題の使用を解決する必要があるjQueryが行うようになったされているもの、これはあなたがCSSのソリューション – guradio

答えて

1

まず、あなたがtabindex属性を追加する必要がありますあなたのdivに、または彼らは決して焦点を受け取ることはできません。

また、子がフォーカスを失ったときに、親からCSSクラスを削除するコードも含まれています。

$("#child").focusin(function() { 
 
    $(this).parent().addClass("focused"); 
 
}); 
 
$("#child").blur(function() { 
 
    $(this).parent().removeClass("focused"); 
 
});
.focused { 
 
    background: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div id="parent" tabindex="-1"> 
 
    Parent Top 
 
    <div id="child" tabindex="-1"> 
 
    Child 
 
    </div> 
 
    Parent Bottom 
 
</div>

+0

私は質問を編集しました – Shesha

+0

これは、すべてのブラウザで ':has'セレクタがサポートされるまで、純粋なCSSで行うことはできません。 –

1

$('#child:focus').parent().addClass('your_class'); 
0

あなたはjQueryのを使用して、この非常に簡単に行うことができます。

$(document).ready(function(){ 
 
if ($(window).width() < 960) { 
 
    $('.child input').on('focus', function(){ 
 
    $('.parent').css({ 
 
    'background-color': 'blue' 
 
    }); 
 
}); 
 
    $('.child input').on('blur', function(){ 
 
    $('.parent').css({ 
 
    'background-color': 'lightgrey' 
 
    }); 
 
}); 
 
} 
 
    
 
});
.parent { 
 
width: 300px; 
 
height: 300px; 
 
display: block; 
 
background: lightgrey; 
 
} 
 
input { 
 
    width: auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
 
<div class="parent"> 
 
    <div class="child"><input type="text"></div> 
 
</div>

+0

をしたいように、私が編集していると思われるでしょう私の質問。 – Shesha

+0

ウィンドウの幅が値よりも小さいかどうかを指定することができるので、必要なすべての画面でそのスタイルを適用できます。私はスニペットを編集しました:) –

1

CSSがレベルアップ選択する選択していない...あなたはJS

関連する問題