[英]How can I make a div appear onclick using Javascript?
我想让 2 个按钮出现 onclick。 我怎么能用 Javascript 做到这一点? 该代码应该询问用户“他们的表现如何?” 然后给他们2个选项可供选择。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function helloName() {
// GET THE USERS INPUT
var userName = document.getElementById("name").value;
// GREET USER WITH THEIR NAME
document.write("Hello " + userName + ", How are you doing today?");
// GIVE USER AN OPTION TO SELECT HOW THEIR FEELING
document.getElementById("show-buttons").style.display = 'block';
};
</script>
</head>
<body>
<h1>JS Skills Test</h1>
<label for="name">Enter Your Name</label>
<input id="name" type="text" placeholder="Enter Your Name">
<button onclick="helloName()">Click Me</button>
<div id="show-buttons" style="display: none;">
<button id="bad">I'm not doing to well</button>
<button id="good">I'm doing wonderful</button>
</div>
</body>
</html>
当你做document.write()
时,所有的 dom 元素都会被删除,试试这个:
function helloName() { // GET THE USERS INPUT var userName = document.getElementById("name").value; // GREET USER WITH THEIR NAME document.getElementById("message").innerText = "Hello " + userName + ", How are you doing today?"; // GIVE USER AN OPTION TO SELECT HOW THEIR FEELING document.getElementById("show-buttons").style.display = 'block'; };
<h1>JS Skills Test</h1> <label for="name">Enter Your Name</label> <input id="name" type="text" placeholder="Enter Your Name"> <button onclick="helloName()">Click Me</button> <div id="message"></div> <div id="show-buttons" style="display: none;"> <button id="bad">I'm not doing to well</button> <button id="good">I'm doing wonderful</button> </div>
您在单击 div 时添加事件侦听器并添加或更改包含可见性或显示属性的 css class。
function helloName() {
const x =
document.getElementById("show-buttons");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
您还可以使用样式可见性:可见; 或可见性:隐藏;
这可以在w3schools.com btw 上找到。
您可以执行以下操作:
function helloName() {
document.getElementById('message').innerText = "Hello"+ userName + ", How are you doing today?";
var x = document.getElementById("show-buttons");
x.style.display="block";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.