使用按钮隐藏和显示 Div
Hide and Show Div with button
伙计们,我正在为我的投资组合尝试一些东西,但我卡住了,我的大脑无法理解我应该做什么,你们能帮忙吗?
所以我隐藏了一个 div 部分,然后单击按钮(更多)应该会显示 div,并且按钮(更多)应该更改为按钮(少)。而且我真的想让它按照我正在做的方式工作,因为我知道它可以工作我只是不太确定如何工作。 enter image description here
enter image description here
您可以使用 HTMLelement.addEventListener
来处理按钮点击事件,并使用 element.style.display
属性 适当地隐藏或显示 div,下面的代码演示了它是如何工作的
const divE = document.getElementById('more');
const btn = document.getElementById('show');
handler = () => {
if (divE.style.display != 'none') {
// if the element is not hidden, hide the element and change button text to "more"
btn.innerHTML = 'More';
divE.style.display = 'none';
} else {
// if the element is hidden, show the element and change button text to "less"
btn.innerHTML = 'Less';
divE.style.display = 'block'
}
}
btn.addEventListener('click', handler)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="show">Less</button>
<div id="more">
IDk something here ig
</div>
</body>
</html>
伙计们,我正在为我的投资组合尝试一些东西,但我卡住了,我的大脑无法理解我应该做什么,你们能帮忙吗?
所以我隐藏了一个 div 部分,然后单击按钮(更多)应该会显示 div,并且按钮(更多)应该更改为按钮(少)。而且我真的想让它按照我正在做的方式工作,因为我知道它可以工作我只是不太确定如何工作。 enter image description here
enter image description here
您可以使用 HTMLelement.addEventListener
来处理按钮点击事件,并使用 element.style.display
属性 适当地隐藏或显示 div,下面的代码演示了它是如何工作的
const divE = document.getElementById('more');
const btn = document.getElementById('show');
handler = () => {
if (divE.style.display != 'none') {
// if the element is not hidden, hide the element and change button text to "more"
btn.innerHTML = 'More';
divE.style.display = 'none';
} else {
// if the element is hidden, show the element and change button text to "less"
btn.innerHTML = 'Less';
divE.style.display = 'block'
}
}
btn.addEventListener('click', handler)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="show">Less</button>
<div id="more">
IDk something here ig
</div>
</body>
</html>