html - 如果用户在文本表单字段中输入文本,如何通过 CSS/HTML 显示其他表单字段?

标签 html css forms hidden-field

我正在尝试找出一种方法来应用 this CSS/HTML 方法,用于在选中单选按钮或复选框时显示其他表单字段,适用于在文本表单字段中输入文本的情况。

我是新手,目前希望避免使用 jquery 和 javascript。

这是“我的”CSS(如果选择了文本表单域,它与“焦点”一起工作,但是一旦用户尝试选择新显示的表单域,它就会消失,因为“焦点”条件不再适用):

.reveal-if-active {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}
input[type="radio"]:checked ~ .reveal-if-active,
input[type="text"]:focus ~ .reveal-if-active,
input[type="checkbox"]:checked ~ .reveal-if-active {
  opacity: 1;
  max-height: 600px; 
  overflow: visible;

我正在寻求帮助的上面的 CSS 行是:

input[type="text"]:focus ~ .reveal-if-active,

这是 HTML:

<div>
    <p>Question I'm asking user to answer in the beginning form field is here</p>
    <div><input type="text" name="beginning-text-field" id="beginning-text-field" value="" placeholder="placeholder text goes here" /><br />
        <div class="reveal-if-active">
        <textarea id="revealed-form-field" name="revealed-form-field" value="" placeholder="Revealed placeholder text goes here" rows="4" maxchar="1000"></textarea>
        </div>
    </div>
</div>

最佳答案

input 不能使用 CSS 中的 :empty 伪类,但是你可以利用 :not :placeholder-shown.将它们结合使用,您可以通过以下方式获得所需的结果:

CSS

.group label, .group input {
    display: block;
}

.elaborate {
    display: none;
    opacity: 0;
}

.question:not(:placeholder-shown) + .elaborate {
    display: block;
    opacity: 1;
}

HTML

<div class="group">
    <label for="q1">Question One</label>
    <input type="text" name="q1_answer" class="question" placeholder="Question 1 Answer" />
    <textarea name="q1_elaborate" class="elaborate" placeholder="Please elaborate"></textarea>
</div>

你可以在这里看到一个 fiddle :https://jsfiddle.net/7zp9pgqL/

:placeholder-shown:not 伪类的使用限制也值得一读:

http://caniuse.com/#feat=css-placeholder-shown

http://caniuse.com/#feat=css-not-sel-list

关于html - 如果用户在文本表单字段中输入文本,如何通过 CSS/HTML 显示其他表单字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529547/

相关文章:

jquery - 我只想在无限轮播中一次滚动一个 Logo

html - float : Block Formatting Context

html - 如何避免重复多个 css 类

html - 您可以在网站的正文内容中使用多个 css 标签吗?

html - XHTML Strict 1.0/CSS 中的 Mozilla float 错误

javascript - 如何在移动设备上设置不缩放?

javascript - 带有圆形 div 的 jQuery 淡入/淡导出吃

jquery 填充单选按钮的 json 数据

mysql - 2个jsp表单保存到一个SaveServlet中

javascript - 在 ExtJS 中,getForm().load() 加载组合字段值吗?