javascript - 居中文本和切换可见性

标签 javascript html css

我正在尝试使用 html/Javascript 将一些文本居中,然后在等待 3 秒后将其在可见和不可见之间切换。我在用 JS 中包含 setTimeout() 的函数,用于在 3 秒后更改显示属性。然而,尽管我尝试了无数解决方案,但文本既不会出现也不会垂直居中。这是我目前所拥有的:

function myfunction() {
  document.getElementsByClassName("parent-class").style.display = "table";
  document.getElementById("h3").style.display = "table-cell";
  setTimeout(function() {
    document.getElementById("h3").style.display = "none";
  }, 3000);
};
myfunction();
.parent-class {
  width: 100%;
  height: 100%;
  text-align: center;
}

.parent-class>h3 {
  vertical-align: middle;
}
<div class="parent-class" style="display:none">
  <h3>+</h3>
</div>

如果我没有为父类设置属性“display:none”,文本(十字)会错误地出现在我程序的第一页上。不知道从这里去哪里,因为感觉我已经尝试了许多显示类型和元素配置。请帮忙!

最佳答案

document.getElementsByClassName("parent-class") 返回元素数组 (getElements)。 document.getElementById("h3") 将不返回任何内容,因为没有 ID h3。

要使文本居中,您是否考虑过 flexboxes?

检查这个 fiddle :https://jsfiddle.net/fokq0btv/

此外,请考虑使用 document.querySelector 而不是旧的 document.getElementBy...

关于javascript - 居中文本和切换可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46608007/

相关文章:

javascript - nuxt 从哪里导入全局模块node_modules

html - 如何在 Safari 浏览器上不使用 CSS 不在 HTML <details> 中显示箭头

javascript - 在一定比例的窗口大小上不断更改 div 大小

javascript - 同时使用力矩和力矩 tz

JavaScript纸牌游戏,如何比较两个字符串中的纸牌?

android - 在 WebView html 问题中设置字体样式

jquery - 显示字体符号的问题

html - 如何在 Rails 中使用 'dynamic CSS'

javascript - 为什么在使用 jQuery 调整大小时不能使用 CSS 类以百分比指定 div 高度?

javascript - 如何将 meteor collection.find() 与排序、跳过和限制一起使用