繁体   English   中英

使用CSS选中/取消选中复选框时切换文本和文本框

[英]Toggle Text and Textbox when Checkbox is checked/unchecked using CSS

在我的HTML程序中,我正在尝试实现一个文本问题“您今天锻炼了吗?”的功能。 然后是一个复选框。 如果选中该复选框,则我希望出现一个新行,询问:“您锻炼了多长时间?” 然后是文本框。 我目前拥有可以实现我的目标的CSS,但是它只能切换文本框,并且可以显示出您持续工作了多长时间。 如何隐藏文本和文本框? 这是我的CSS代码:

function $_(IDS) { return document.getElementById(IDS); }
function toggle(Info) {
var CState = $_(Info);
if (CState.style.display != "none") { CState.style.display = "none"; }
                               else { CState.style.display = "inline"; }
}
function HideElem(IDS1, IDS2) {
  toggle(IDS1);
  toggle(IDS2);
}

function inputFocus(i){
    if(i.value==i.defaultValue){ i.value=""; i.style.color="#000"; }
}
function inputBlur(i){
    if(i.value==""){ i.value=i.defaultValue; i.style.color="#888"; }
}

这是用HTML实现的:

Did you work out today? <div class="checkboxFour">
  <input type="checkbox" value="1" onchange = "HideElem('share','meal')" id="checkboxInput" name="" />
  <label for="checkboxInput"></label>
  </div>
  <span id= "share">
    </span> <br><br>How long did you work out? <input type="text" id="meal" name="meal" size="40" style="display:none;" 
    value="Example: 8.5 Hours" onfocus="inputFocus(this)" onblur="inputBlur(this)">

我还使用了一个风格化的复选框,如果这会改变情况。 谢谢你的帮助。

您不能将css样式添加到文本节点(标题),因此将标题和输入元素包装在另一个元素中并将可见性应用于该包装元素

<input type="checkbox" value="1" onchange="HideElem('share','mean-ct')" id="checkboxInput" name="" />

然后

<span id="mean-ct" style="display:none;">
    How long did you work out?
<input type="text" id="meal" name="meal" size="40" value="Example: 8.5 Hours" onfocus="inputFocus(this)" onblur="inputBlur(this)" />
</span>

演示: 小提琴

使用span标记包裹您的问题并为其指定id 。尝试以下操作:

HTML:

<span id="how" style="display:none;">How long did you work out? </span>

javascript:

if (CState.style.display != "none") { 
  CState.style.display = "none"; 
  document.getElementById("how").style.display = "none"; //hide the question
}
else { 
    CState.style.display = "inline"; 
    document.getElementById("how").style.display = "inline"; //display the question
}

演示版

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM