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

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

本文关键字:文本 复选框 选中 CSS 取消 使用      更新时间:2024-02-11

在我的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>

演示:Fiddle

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
}

演示