[英]Checkboxes to toggle text on and off
I want to use a checkbox to change the visibility of a paragraph in JavaScript. 我想使用复选框更改JavaScript中段落的可见性。 I would like to do this in pure JavaScript and not use any librararies like jQuery. 我想用纯JavaScript做到这一点,而不要使用jQuery之类的任何库。 Furthermore, I would like to do it in JSFiddle. 此外,我想在JSFiddle中做到这一点。
I know that one viable solution is to use: document.formName.checkboxName.checked like so: 我知道一个可行的解决方案是使用:document.formName.checkboxName.checked像这样:
function show {
document.getElementById("paragraphName").style.visibility=(document.formName.checkboxName.checked) ? "visible" : "hidden";
}
but this solution does not work in JSFiddle. 但是此解决方案在JSFiddle中不起作用。
How do I go about doing this? 我该怎么做呢?
try this.. 尝试这个..
window.onload = function init() {
checkbox = document.getElementById("checkbox1");
checkbox.checked = true;
checkbox.onchange = function(){
document.getElementById("first").style.display = checkbox.checked?'block':'none';
}
}
The HTML HTML
<label><input id="chk1" name="chk1" type="checkbox" onclick="nhamnham()"/>Hide p</label>
<p id="par">Text in the paragraph...</p>
The JS JS
function nhamnham() {
if(document.getElementById("chk1").checked) {
document.getElementById("par").style.visibility="hidden";
} else {
document.getElementById("par").style.visibility="visible";
}
}
You need to call the init()
function{as per the fiddle link you provided} on onclick
of checkbox: 您需要在复选框的onclick
上调用init()
函数(根据您提供的小提琴链接):
<form name="formex">
<input id="checkbox1" type="checkbox" name="firstpara" onclick="init();" />First paragraph<br/>
</form>
<p id="first">This is a paragraph</p>
And JS be like: 和JS一样:
function init() {
if(document.getElementById("checkbox1").checked === false) {
document.getElementById("first").style.display = 'none';
}
else
document.getElementById("first").style.display = 'block';
}
You can try a CSS-only solution: 您可以尝试仅CSS的解决方案:
#toggler ~ #toggler-target { display: none; } #toggler:checked ~ #toggler-target { display: block; }
<input type="checkbox" id="toggler" /> <label for="toggler">Toggle</label> <p id="toggler-target">Foo bar baz</p>
var par = document.getElementById('par'); document.getElementById('chk1').addEventListener('change', function() { par.style.visibility = this.checked ? "hidden" : "visible"; });
<label><input id="chk1" name="chk1" type="checkbox">Toggle</label> <p id="par">Text in the paragraph...</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.