簡體   English   中英

聚焦時為父元素應用樣式

[英]Apply style for parent element when it is focused

 **CSS**

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

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

當孩子集中注意力時,這是為父母應用樣​​式的正確方法嗎?

編輯:我的問題是我需要將這些樣式應用於小型設備。 所以我不能使用Jquery。 這就是為什么我要在CSS中進行媒體查詢的原因。

您也可以為此使用jQuery:

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

首先,您需要向div添加一個tabindex屬性,否則它們將永遠無法獲得焦點。

我還包含了當孩子失去焦點時從父級刪除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> 

CSS沒有選擇器來選擇上級...您需要使用JS解決您的問題

對於這個特殊的需求是:focus-within CSS中實現的:focus-within偽類。 在您的示例中,以下CSS將完成您嘗試完成的工作。 我將tabindex添加到#child以使div可以#child 對於本機可聚焦的元素(例如,鏈接或表單元素)而言,這不是必需的。 但是,IE和Edge不支持它。 在計划切換到Blink渲染引擎之后,Edge將支持它。

另請參閱此CSS技巧文章

 #parent { padding: 0.25em; background-color: crimson; } #parent:focus-within { color: white; } 
  <div id="parent"> <h1>Parent</h1> <div id="child" tabindex="0"> <p>Child (click me!)</p> </div> </div> 

您可以使用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> 

這可以通過與jQuery實現相同的4級selecor偽類實現

#parent:has(> #child) { /* styles to apply to the #parent */ }

但這當前不被瀏覽器支持

為什么我們沒有父選擇器

暫無
暫無

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

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