【问题标题】:Change background position div when input is focus输入焦点时更改背景位置 div
【发布时间】:2012-06-09 16:36:10
【问题描述】:

我正在用像标签这样的图像构建表单......

我有:

DIV.icon-phone {
    width: 22px
    height: 22px
    background: url('icon-set.png') no-repeat 22px 66px;
}

INPUT.pool-phone {
    border:1px solid #666;
}

我想要这样的: if INPUT.pool-phone:focus 将 DIV.icon-phone 背景位置更改为:44px 66px

请帮忙。

【问题讨论】:

    标签: css html input background focus


    【解决方案1】:

    为了在修改另一个元素时改变一个元素的某些 css 属性,您需要具有特定的结构..

    对于您的示例,input 元素必须与 div 共享相同的直接父级,并且在层次结构中也位于它之前。

    在这种情况下,您可以使用~ General sibling combinator 来定位它

    .pool-phone:focus ~ .icon-phone{
       background-position:...
    }
    

    演示地址 http://jsfiddle.net/gaby/fx5Uy/


    否则您可以使用 javascript 并绑定到 onfocus 事件..

    【讨论】:

      【解决方案2】:

      您可以编写一个 javascript 函数来为您处理。

      [the input button].onfocus = function changeBg () { [thediv].style.background="[whatever you want]" };
      [the input button].onblur = function resetBg () { [thediv].style.background="[whatever you want]" };
      

      Gaby 发布了一个更可取的纯 css 版本(至少对我而言)。

      【讨论】:

      • 好的,但我有 8 个带池的 div,这是很大的代码量。我可以使用类似:“+”或“
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 2013-01-02
      • 1970-01-01
      相关资源
      最近更新 更多