[英]How do you change a CSS property in a javascript file?
我想知道如何在输入正确的密码时将 lock:before 的边框更改为纯透明。
我的JavaScript是这样的,触发IF时,我需要在value之前加锁才能变为solid透明
function lock(){
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
alert("Lock opened");
} else {
alert("Wrong password");
}
}
我的CSS是这样的,需要通过javascript函数将之前的锁定更改为实体透明。
body {
position: absolute;
color: #00ff80;
background: green;
top: 100px;
left: 200px;
}
#lock {
font-size: 8px;
position: relative;
width: 18em;
height: 13em;
border-radius: 2em;
top: 10em;
box-sizing: border-box;
border: 3.5em solid red;
border-right-width: 7.5em;
border-left-width: 7.5em;
margin: 0 0 6rem 0;
}
#lock:before {
content: "";
box-sizing: border-box;
position: absolute;
border: 2.5em solid red;
width: 14em;
height: 12em;
left: 50%;
margin-left: -7em;
top: -12em;
border-top-left-radius: 7em;
border-top-right-radius: 7em;
}
#lock:after {
content: "";
box-sizing: border-box;
position: absolute;
border: 1em solid red;
width: 5em;
height: 8em;
border-radius: 2.5em;
left: 50%;
top: -1em;
margin-left: -2.5em;
}
#button {
background: transparent;
}
我的 HTML 是这样的,它所做的只是制作一个按钮和一些文本。
<!DOCTYPE html>
<html>
<head>
<title>The lock</title>
</head>
<body>
<h1>Unlock the lock</h1>
<button id=button onclick="lock()"><div id=lock></div></button>
</body>
</html>
尝试这样的事情..
var str = '1em solid transparent';
document.styleSheets[0].addRule('#lock:before','border: "'+str+'";');
伪元素的样式可以通过使用新的类名来改变。 例如,一旦输入的密码有效, #lock
unlocked
的类名添加到#lock
元素。
您可以为新类添加以下样式:
#lock.unlocked::before {
border: 1em solid transparent;
/* Your style for unlocked goes here */
}
以及您的脚本与添加类.unlocked
的新指令。
function lock() {
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
alert("Lock opened");
document.getElementById("lock").classList.add("unlocked"); /* NEW */
} else {
alert("Wrong password");
}
}
在按钮中添加和删除类。 伪元素不能直接从 JavaScript 定位,因此您必须使用 CSS 来更改样式。
// Select the button
const button = document.querySelector('button');
function lock(){
alert("It's locked, you have to guess the password.");
var pass = prompt("");
if (pass == "opensesame") {
// Add the class.
button.classList.add('unlocked');
// If it already has the class..
} else if (button.classList.contains('unlocked')) {
//.. then remove it.
button.classList.remove('unlocked');
}
}
并在您的 CSS 中添加具有您需要的样式的类。
#lock.unlocked::before {
border: 2.5em solid transparent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.