簡體   English   中英

如果它的子元素被聚焦,我如何隱藏一個 div?

[英]How do I shadow a div if it's child element is focused?

我基本上希望 searchBarFirstDiv 在選擇 searchBarInput 時形成陰影

我正在使用反應。

這是我的 HTML 供參考:

 <div className={css.searchBarFirstDiv}> <label className={css.searchBarDivContent} for="location-search-input"> <div className={css.searchBarHeadingFont}>Location</div> <input id="location-search-input" placeholder="Where are you going?" className={css.searchBarInput} /> </label> </div>

我該怎么做呢?

純CSS溶液

 #main { padding: 30px; margin: 31px; } #main:focus-within { box-shadow: 0px 0px 10px red; }
 <div id="main"> <input type="text" id="input" placeholder="focus me!"> </div>

香草 JS 方法:

document.getElementsByClassName('searchBarInput')[0]
.addEventListener('focus', function(){
  
    triggerFocus(document.getElementsByClassName('searchBarFirstDiv')[0]);

});

// Thanks to: https://stackoverflow.com/a/52450494/1352994
function triggerFocus(element) {
    var eventType = "onfocusin" in element ? "focusin" : "focus",
        bubbles = "onfocusin" in element,
        event;

    if ("createEvent" in document) {
        event = document.createEvent("Event");
        event.initEvent(eventType, bubbles, true);
    }
    else if ("Event" in window) {
        event = new Event(eventType, { bubbles: bubbles, cancelable: true });
    }

    element.focus();
    element.dispatchEvent(event);
}

暫無
暫無

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

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