首页 > 解决方案 > 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>

标签: javascripthtml

解决方案


改用<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>


推荐阅读