【问题标题】:Change translateY of element on input focus在输入焦点上更改元素的 translateY
【发布时间】:2015-06-12 18:18:24
【问题描述】:

当用户专注于输入时,我正在尝试对元素应用效果。我读过我可以通过使用 css 选择器(+、~、>)在不使用 jQuery 的情况下实现这一点。那么问题是客户端使用Contact From 7 呈现大量代码。

这里是代码

<div class="theInput">
    <span class="wpcf7-form-control-wrap your-name">
        <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required effectForm" aria-required="true" aria-invalid="false" />
    </span>
    <span class="theLabel" id="your-name">Name</span>
</div>

如您所见,“spans”来自联系表格 7。我正在尝试使用 css 选择器“+”翻译类 theLabel

到目前为止我已经尝试过什么

最后的想法是尽可能详细地介绍课程

span.wpcf7-form-control-wrap.your-name input.wpcf7-form-control.wpcf7-text.wpcf7-validates-as-required.effectForm:focus + .theLabel{
    transform:translateY(-25px);
    }

一个想法是通用的

input:focus + .theLabel

其他想法过于笼统

input:focus .theLabel

还有很多其他的组合,都失败了。我知道我做错了什么。但我找不到什么。

谢谢你:)

【问题讨论】:

    标签: html css


    【解决方案1】:

    您正在尝试使用 CSS 选择父元素的同级元素。请参阅此相关答案:CSS: how to select parent's sibling

    如果您可以编辑 HTML,则可以将输入 HTML 元素移动到与 span.theLabel 元素相同的 DOM 层次结构级别,以使您能够使用 CSS 同级选择器 (+)。 this fiddle 中有一个示例。

    HTML

    <!-- the span wrapper around the input has been removed, moving the input to the same
    DOM tree level. -->
    
    <div class="theInput">
      <input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required effectForm" aria-required="true" aria-invalid="false" />
      <span class="theLabel" id="your-name">Name</span>
    </div>
    

    CSS

    /* Note the display:inline-block needed for the transform to work as well as vendor
    prefixes */
    
    input.wpcf7-text:focus + span {
                display: inline-block;
      -webkit-transform: translateY(-25px);
          -ms-transform: translateY(-25px);
              transform: translateY(-25px);
    }
    

    如果您无法更改 HTML 标记,则需要使用 javascript 来选择 span.theLabel,如顶部链接答案所示。

    【讨论】:

    • 感谢您的回答 :) 不幸的是,我无法更改 html。 (我必须自己编辑插件,并且在第一次更新时它会坏掉)。我最终为此使用了 JS。
    最近更新 更多