如果选中了复选框,则使用JavaScript更改CSS可见性 [英] Changing CSS visibility with JavaScript if a checkbox has been checked

查看:94
本文介绍了如果选中了复选框,则使用JavaScript更改CSS可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码段中,选中此复选框时,蓝色div应该隐藏。但是,事实并非如此。我尝试了很多不同的语法,但到目前为止还没有运气。

In the snippet below, blue div should hide when the checkbox is checked. Yet, it doesn't. I've tried a lot of different syntax, but no luck so far.

if (document.getElementById("check".checked = "true")) {
      document.getElementById("box").style.visibility = "hidden";
}

#box {
      background: lightblue;
      width: 200px;
      height: 200px;
}

<input type="checkbox" id="check">
<div id="box"></div>

推荐答案

这就是您想要的。 http://jsfiddle.net/3ywqy72w/8/

上面放置的代码有很多问题。

There were many problems with the code you have placed above.

在HTML中,您需要为javascript调用一个函数,以选中此复选框被点击。看起来像这样:

In the HTML, you need to call a function for javascript to do something once the checkbox is clicked. That looks like this:

<input type="checkbox" id="check" onclick="toggleBoxVisibility()">

在Javascript中,您也没有创建用于使代码在调用onClick。看起来像这样:

In the Javascript, you also did not create the function that will be used to make code happen once the onClick is called. This is what that looks like:

function toggleBoxVisibility() {

if (document.getElementById("check").checked == true) {

    document.getElementById("box").style.visibility = "visible";

    } 
else {

    document.getElementById("box").style.visibility = "hidden";

    }
}

请注意一些语法。在您的代码中,只有一个 =设置了一个值。在if语句中,这将不起作用。要比较值,必须使用上面显示的两个值。

Note some of the syntax. In your code, there was only one "=" which sets a value. This will do nothing in an if statement. To compare values, you must use two as shown above.

最后,您只检查一次以查看是否已选中该复选框,而不是相反。那只会工作一次,永远不会显示相反的情况。

Lastly, you were only checking once to see if the checkbox was checked and not the other way around. That would only work once and would never display the opposite case.

这篇关于如果选中了复选框,则使用JavaScript更改CSS可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆