我需要在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 = "";
}
}
问题:
-
变量
password
是在函数外部声明的,因此不需要作为参数传递。 -
我将
password
变量更改为仅包含对#password
元素本身的引用,以便您可以在以后更改时获取其值。 -
将
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>