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>替代

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包含需要显示的值的。然后,您无需一遍又一遍地重复该功能。就像是:

[...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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章