javascript - 将文本更改为隐藏和显示的按钮
问题描述
我在一个名为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>
我希望当我第一次按下按钮时,它会显示提示字段的内容,当我第二次按下它时,它会隐藏它,依此类推......
提前致谢
解决方案
以您的风格和总体思路的贡献,它是在您的脚本中添加一小部分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>
-->
推荐阅读
- java - 使用 Google Cloud Vision 人脸检测 API 时出错
- c# - 带有sql参数的sqlcommand c#方法
- regex - 获取正则表达式以匹配同一模式的多个实例
- java - c++ 是否提供与 java 中的 threadLocal 提供相同支持的任何内置类?
- c - OpenMP 线程,如何正确使用 omp atomic 子句?
- r - 将两个图合并为一个(添加边)R igraph
- node.js - 在 React 中服务不同的页面是如何工作的?
- vue.js - 在 Vue.js 应用程序中正确设置环境变量
- javascript - 量角器承诺调用如何执行函数调用
- proxy - Dante Socks5 代理服务器无法启动