【问题标题】:css on focus change another div's stylingcss on focus 改变另一个 div 的样式
【发布时间】:2018-10-21 00:52:11
【问题描述】:

我希望 svg 在用户关注输入时更改填充颜色。 但我不明白如何编写 css 来实现它。 添加了 Html 和 css 供您查看!我正在为 css 使用 scss。

<div class="search">
    <svg width="20px" height="20px" viewBox="0 0 88 88" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <g id="Symbols" stroke="none" stroke-width="1" fill-rule="evenodd">
            <g id="Icon-Search" fill="#b3b3b3" fill-rule="nonzero">
                <path d="M86.829,81.172 L64.128,58.471 C69.055,52.312 72,44.5 72,36 C72,16.118 55.883,0 36,0 C16.118,0 0,16.118 0,36 C0,55.882 16.118,72 36,72 C44.5,72 52.312,69.054 58.471,64.127 L81.172,86.828 C81.953,87.609 82.977,88 84,88 C85.024,88 86.048,87.609 86.829,86.828 C88.391,85.267 88.391,82.733 86.829,81.172 Z M36,64 C20.536,64 8,51.464 8,36 C8,20.536 20.536,8 36,8 C51.465,8 64,20.536 64,36 C64,51.464 51.465,64 36,64 Z" id="Shape"></path>
            </g>
         </g>
      </svg>

      <input class="input inputSearchField" type="text" placeholder="Search...">
  </div> 



.input{
    width: 250px;
    height: 35px;
    padding-left: 16px;
    font-weight: 700;
    background-color: $white-color;
    border-radius: 4px;
    border: 1px solid $lighter-gray;
    font-size: 16px;
    outline:none;
    transition: all 0.30s ease-in-out;
    &::placeholder {
        color: $light-gray;
    }
    &:focus {
        box-shadow: 0 0 5px #64e469;
        border: 1px solid #64e469;
    }
}
.search { 
    position: relative;
    margin: 0 auto;
    text-align: center;
    width: 270px;
    margin-bottom: 30px;
  }
  .search svg { 
    position: absolute;
    top: 7px;
    right: 22px;
    fill: $lighter-gray;
  }

【问题讨论】:

  • 我们还需要相关的 HTML 以提供适当的帮助
  • 你的 HTML / SVG 是什么样子的?
  • 如果svg和input标签是兄弟,可以通过input:focus ~ svg {}

标签: html css svg sass focus


【解决方案1】:

我想知道您是否有类似的 html:

<div class="search">
  <input class="input" />
  <svg />
</div>

你的 css 可以是这样的:

.input:focus + svg { ... }

如果svg 出现在input 之前,那么您可以使用~ 代替+

【讨论】:

    【解决方案2】:

    看看这个 CodePen Demo。您需要在 之前 移动您的 SVG 输入,否则您将不得不使用一些 JavaScript 来执行此操作,因为 CSS 没有任何类型的“向后看”选择器。甚至General Sibling Combinator 也只会向前看当前选择器目标。

    如果你先移动输入,你可以这样做:

    .input:focus + svg #Icon-Search {
      fill: #64e469;
    }
    

    如果您确实想要保留当前结构,JavaScript 将类似于 Demo

    let search  = document.getElementsByClassName('inputSearchField');
    let svgFill = document.getElementById('Icon-Search');
    
    search[0].onfocus = function(){ svgFill.style.fill = '#64e469'; }
    search[0].onblur  = function(){ svgFill.style.fill = '#b3b3b3'; }
    

    你可以看到它有点乏味!

    【讨论】:

    • 我的荣幸!我也更新了答案,以显示如果您保留当前结构并使用 JavaScript 作为参考,它会是什么样子。很高兴为您提供帮助!
    • 酷 :) 谢谢!
    猜你喜欢
    • 2013-07-14
    • 2014-07-20
    • 2016-10-01
    • 2011-12-14
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多