首页 > 解决方案 > 将文本更改为隐藏和显示的按钮

问题描述

我在一个名为Anki的应用程序中使用了这段代码,这是一个可以帮助我记住新单词的抽认卡应用程序。我有这段代码,当我点击它时会写一个文本,它显示了我在添加新卡时添加的提示字段的内容,

{{#Hint}}
    <div id="hint" class="hidden">
        <p class="trigger">[ click to show hint ]</p>
        <p class="payload">{{Hint}}</p>
    </div>
    <script>
        var hint = document.getElementById('hint');
        hint.addEventListener('click', function() { this.setAttribute('class', 'shown'); });
    </script>
{{/Hint}}

例如,我想要的只是将上面的文本的函数写入具有这种代码样式的按钮。

<!DOCTYPE html>
<html>
<head>
<style>
.button {
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

.button1 {background-color: #4CAF50;} /* Green */
</style>
</head>
<body>

<button class="button button1">Green</button>

</body>
</html>

我希望当我第一次按下按钮时,它会显示提示字段的内容,当我第二次按下它时,它会隐藏它,依此类推......

提前致谢

标签: javascripthtmlcssanki

解决方案


以您的风格和总体思路的贡献,它是在您的脚本中添加一小部分js。

关于@munleashed 所说的,它也可以被onclick事件使用。

var hint = document.getElementById('hint');

function hide() {
  hint.classList.toggle('shown');
}
.button {
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
.button1 {
  background-color: #4CAF50;
}
#hint .payload {
  display: none;
}
#hint.shown .payload {
  display: block;
}
<div id="hint" class="hidden">
  <button class="button button1" onclick="hide()">[ TOUCH ]</button>
  <p class="payload">SOME HINT HERE</p>
</div>
<!-- 
<button class="button button1" onclick="hide()">[ TOUCH ]</button>

<div id="hint" class="hidden">
    <p class="payload">SOME HINT HERE</p>
</div> 
-->


推荐阅读