javascript - Javascript标签位置
问题描述
我正在研究一个莫尔斯电码训练器。有 26 个音频元素 (AZ),每个元素都有一个隐藏或显示字母的按钮。下面列出了代码,为简洁起见,只有一个字母。
我的问题是当字母的显示被切换时,它会在打印值之前强制换行。我希望这封信直接出现在按钮的右侧,消除了换行符。更好的是,让每个按钮的文本在“显示”和元素的字母之间切换。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CW Practice</title>
</head>
<body>
<script>
function aFunction() {
var x = document.getElementById("aDIV");
if (x.innerHTML === "") {
x.innerHTML = "A";
} else {
x.innerHTML = "";
}
}
// followed by bFunction, cFunction, etc.
</script>
<audio controls>
<source src="a.wav" type="audio/wav">
</audio>
<button onclick="aFunction()">Show <div id="aDIV"></div> </button>
<br>
</body>
</html>
解决方案
改用<span>
a
function aFunction() {
var x = document.getElementById("aDIV");
if (x.innerHTML === "") {
x.innerHTML = "A";
} else {
x.innerHTML = "";
}
}
<button onclick="aFunction()">Show <span id="aDIV"></span> </button>
或者如果它真的必须是,<div>
你可以将它设置为display: inline-block;
function aFunction() {
var x = document.getElementById("aDIV");
if (x.innerHTML === "") {
x.innerHTML = "A";
} else {
x.innerHTML = "";
}
}
#aDIV {
display: inline-block;
}
<button onclick="aFunction()">Show <span id="aDIV"></span> </button>
现在是有趣的部分:您可以使用data-attribute
包含您需要显示的值的 a。然后你就不需要一遍又一遍地重复这个功能。就像是:
[...document.querySelectorAll('[data-placeholder]')].forEach( item => {
item.addEventListener('click', (event) => {
event.preventDefault();
var x = item.querySelector('.placeholder');
// this one liner is the same as your if / else
x.innerHTML = x.innerHTML === "" ? item.dataset.placeholder : "";
});
});
.placeholder {
padding: 0 0 0 5px;
}
<button data-placeholder="A">Show<span class="placeholder"></span></button>
<button data-placeholder="B">Show<span class="placeholder"></span></button>
<button data-placeholder="C">Show<span class="placeholder"></span></button>
推荐阅读
- c++ - 如何设置 SFML+CMake+代码块?
- elasticsearch - 在集群上的重负载时刻,Elasticsearch 是否会产生不准确的聚合?
- mysql - 实体继承模型中的MySql选择查询,如何?
- javascript - 一些特定的架构或设计模式?
- html - PrimeNG 组件菜单步骤,我如何使用 ui-steps-incomplete
- java - 检测与线的碰撞并限制移动
- linux - Linux SHELL 脚本,读取每一行的不同列数
- python - 使用python将未训练的对象分类为机器学习中的未知对象
- javascript - 使用观察者设计模式的理由
- android - 无法解决:com.google.android.gms:play-services