如何在 JavaScript 函数中居中文本

How to Center Text in a JavaScript Function?

本文关键字:中居 中文 文本 函数 JavaScript      更新时间:2023-09-26

我有一个JavaScript函数,它根据文本字段中的输入显示文本。在文本字段中输入值时,我的程序将检查该值是否正确。如果正确,我的程序显示"你是对的!"如果不正确,我的程序显示"再试一次!">

文本字段和按钮都在页面上水平居中,但我不知道如何将"你是对的!"和"再试一次!"居中。

我觉得我已经尝试了一切,但显然我没有,考虑到我无法让它工作。

这是我的JavaScript函数的代码:

<center><p>Can you remember how many books I listed at the bottom of the page?</p></center>
<center><input id="numb"></center>
<center><button type="button" onclick="myFunction()">Submit</button></center>
<p id="demo"></p>
<div class="jsFunction">
<script>
function myFunction() 
{
    var x, text;
    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;
    // If x is Not a Number or less than five or greater than five
    if (isNaN(x) || x < 5 || x > 5) 
    {
        text = "Try again!";
    } 
    else 
    {
        text = "You are correct!";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>
</div>

以下是该函数的 CSS 代码:

.jsFunction
{
    margin-left: auto;
    margin-right: auto;
}

这个特定的CSS代码只是我在函数中使文本居中所做的许多尝试之一。

这是一张图片的链接,它将向您展示我遇到的问题:https://i.stack.imgur.com/Hb01j.png

请帮忙!

尝试在包含text-align: center;p 标记上设置类

编辑

script嵌套在div中毫无意义,因为script标签不会被呈现

您可以在 css 中定位#demo(用于文本对齐方式(,也可以添加包含正确样式的类align-center

我会推荐后者,因为它变得更加可重用,而您不能在同一页面上重用id

你使用 JavaScript 的事实对这个问题并不重要。我之所以提到它,是因为标题"如何在 JavaScript 函数中居中文本",以及您试图将包含 JavaScript 代码的实际脚本元素居中。

你想让一个恰好由 JavaScript 控制的元素的内容居中,但答案是仅限 CSS。

正如Ryuu的回答所提到的,text-align: center将完成(你猜对了(文本和其他内联级内容的工作。

不应使用已弃用的 center 标记。

如果您尝试使用边距,则将其应用于正确的元素并且该元素具有宽度,则某些内容将居中。然而,那个"东西"是元素,而不是元素的内容。

换句话说,边距可用于对齐框,而不是框内的内容。

示例 1:元素居中,但文本仍左对齐。

示例 2:将元素及其内联级内容居中。

.margin-example1 {
  width: 200px;
  background-color: #ddd;
  /* shorthand for margin: 0 auto 0 auto, which is shorthand for specifying each side individually */
  margin: 0 auto;
}
.margin-example2 {
  width: 200px;
  background-color: #aaccee;
  margin: 0 auto;
  /* we still need this to get the desired behavior */
  text-align: center;
}
<div class="margin-example1">Example 1</div>
<div class="margin-example2">Example 2</div>

那么文本输入呢?浏览器通常将输入样式设置为display:inline-block。这意味着我们可以在它们内部居中(示例 1 和 2(,但要将它们集中在它们的容器中,我们需要更改为 display:block(示例 3(,或者因为它们本身就是类似内联的元素,我们可以在父容器上设置text-align(示例 4(,另请参阅。

.example1 {
  width: 100%;
  text-align: center;
}
.example2 {
  width: 200px;
  text-align: center;
}
.example3 {
  display: block;
  width: 200px;
  text-align: center;
  margin: 0 auto;
}
.example4 {
  width: 200px;
  text-align: center;
}
.example4-parent {
  text-align: center;
}
<div>
  <input type="text" value="Example 1" class="example1">
</div>
<div>
  <input type="text" value="Example 2" class="example2">
</div>
<div>
  <input type="text" value="Example 3" class="example3">
</div>
<div class="example4-parent">
  <input type="text" value="Example 4" class="example4">
</div>

CSS 中的布局可能很复杂,但基础知识并不难。

请注意,我过度简化了我的解释/定义(准备好后,您可以阅读有关格式化模型的所有信息(。