HTML和JavaScript密码:如果密码正确,如何更改元素的显示?



我需要在Javascript的帮助下在HTML中制作一个受密码保护的图像,这意味着,如果你输入正确的密码,就会出现一个图像。我是初学者,所以我找不到任何错误。我什至不知道这段代码是否写得很好,所以如果你能提供帮助,我将不胜感激。

.HTML:

<img src="..." id="smiley"/>
<form>
This picture is password protected<br>Enter a password:<br>
<input type="password" name="password" id="password">
<input type="button" onclick="funcPass( );" value="Ok">
</form>

JavaScript:

var password = getElementById("password").value;
function funcPass(password.value) {
if (password.value == "smiley")
{
document.getElementById("smiley").style.display = "block";
}
else
{
password.value = " ";
}
}

CSS中,我将图像显示属性更改为无

获取密码的代码需要在函数本身中。您还将获得两次值(值的值(。试试这个:

function funcPass() {
var password = document.getElementById("password").value;
if (password == "In A Darkened Room")
{
document.getElementById("smiley").style.display = "block";
}
else
{
password = "";
}
}

问题:

  1. 变量password是在函数外部声明的,因此不需要作为参数传递。

  2. 我将password变量更改为仅包含对#password元素本身的引用,以便您可以在以后更改时获取其值。

  3. getElementById更改为document.getElementById以阻止其引发错误。

下面是一个功能演示:

var password = document.getElementById("password");
function funcPass() {
if (password.value == "In A Darkened Room") {
document.getElementById("smiley").style.display = "block";
} else {
password.value = "";
}
}
img {
border: 1px solid red;
width: 50px;
height: 50px;
display: none;
}
<img src="..." id="smiley" />
<form>
This picture is password protected<br>Enter a password:<br>
<input type="password" name="password" id="password">
<input type="button" onclick="funcPass();" value="Ok">
</form>

最新更新