【问题标题】:How to change the background color of the div while focusing the text Input field?如何在聚焦文本输入字段的同时更改 div 的背景颜色?
【发布时间】:2021-02-11 15:00:39
【问题描述】:

在渲染中,

 <div id="container" tabindex="0">
    <input id = "input" type="text" />
  </div>

在css中,

#container::focus{
 background-color: "red"
}

聚焦输入字段时,我需要将 bg-clr 固定在 div 中。

【问题讨论】:

    标签: javascript html css reactjs background-color


    【解决方案1】:

    尝试使用:focus-within CSS 伪类

    :focus-within CSS 伪类表示具有 获得焦点或包含获得焦点的元素。

    #container:focus-within {
      background-color: red;
    }
    
    #container {
      padding: 30px;
    }
    <div id="container" tabindex="0">
      <input id="input" type="text" />
    </div>

    注意:如果不想关注div#container直接去掉tabindex

    【讨论】:

    【解决方案2】:

    如果您已准备好使用 JavaScript,那么这就是唯一的解决方案。根据要求,您可以将颜色设置为 Focus 和 Blur 事件。

    $(document).on('focus','.input', function() {
    $("#container").css("background-color","black");
    })
    
    $(document).on('blur','.input', function() {
    $("#container").css("background-color", "white");
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="container">
        <input class="input" id="input" type="text" />
      </div>

    【讨论】:

      【解决方案3】:

      然后你需要给元素添加一个 onfocus 事件

       <div id="container" tabindex="0">
          <input id = "input" type="text" onfocus="myFunction(this)" />
      
      <script>
      function myFunction(item) {
          item.style.backgroundColor = 'red';
      }
      </script>
      

      查看此页面了解更多信息: https://www.w3schools.com/jsref/event_onfocus.asp

      【讨论】:

        【解决方案4】:

        css 无法实现您想要实现的目标。您需要在input 上使用JavaScript focusblur 事件监听器来更改div 的背景颜色:

        document.querySelector('#input').addEventListener('focus', function(e) {
            e.target.closest("#container").classList.add('focus');
        })
        document.querySelector('#input').addEventListener('blur', function(e) {
            e.target.closest("#container").classList.remove('focus');
        })
        

        CSS:

        #container.focus{
         background-color: "red"
        }
        

        【讨论】:

          猜你喜欢
          • 2011-09-10
          • 2018-03-24
          • 1970-01-01
          • 2021-09-26
          • 2011-11-28
          • 2018-03-09
          • 2011-11-05
          • 2018-03-03
          相关资源
          最近更新 更多