【问题标题】:Hide and Show Div with button [duplicate]使用按钮隐藏和显示 Div [重复]
【发布时间】:2021-12-06 05:23:22
【问题描述】:

伙计们,我正在为我的投资组合尝试一些东西,但我被卡住了,我的大脑无法理解我应该做什么,你们能帮忙吗?

所以我有一个要隐藏的 div 部分,然后单击 BUTTON(More) 应该显示 div,并且 BUTTON(More) 应该更改为 BUTTON(LESS)。我真的想让它按照我的方式工作,因为我知道它可以工作,但我不太确定如何工作。 enter image description here

enter image description here

【问题讨论】:

标签: javascript html ecmascript-6


【解决方案1】:

您可以使用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>

【讨论】:

  • 嗨所以由于某种原因它没有切换隐藏并在 btn 上显示它取消隐藏但是如果我单击 btn agian 来隐藏它它不会这样做?
  • 我刚刚再次检查了运行我的 sn-p,它对我有用
  • 是的,我看到你的作品,但对我来说,我不知道为什么而且我没有收到错误让我在这里发布,我如何给你看截图?
  • 在你的代码中你实际上并没有切换任何东西,你只是在记录消息
  • 用我的替换你的javascript文件,用你的元素ID替换getElementById参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2011-08-21
  • 2023-03-26
  • 2013-07-06
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多