javascript - 如何使用或不使用 javascript 在数字之间添加垂直线?

标签 javascript css debugging

我创建了一个计时器来倒计时到特定日期,它显示没有问题。但是这一次,我想添加垂直线来分隔它们。我试图通过 borderLeftheight 来查看垂直线,但没有成功。不过,我确实看到了 1px solid 边框。下图说明了我想在浏览器中看到的内容。

enter image description here

我还希望文字(天、小时、分钟、秒)显示在数字下方。根据图片,它直接出现在他们旁边。我尝试使用 \n 因为我认为它会将单词放在一个新行中,但这没有用。

我们甚至需要使用 javascript 来实现这些东西吗?我做错了什么,我该如何解决?

这是我的js:

var timerDisplay = document.getElementById("timer");
    timerDisplay.innerHTML = days + "\ndays " + hours + "\nhours " + minutes + "\nminutes " + seconds + "\nseconds ";
    timerDisplay.style.border = "1px solid";
    timerDisplay.style.borderLeft = "6px solid"
    timerDisplay.style.height = "10px";

这是我的 html:

<p id="timer"></p>

最佳答案

您可以将内联元素添加到 p 中,从而可以应用一些样式来实现您的目标。

例如:

const timerDisplay = document.querySelector("#timer")
timerDisplay.appendChild(createSpan('126 days'))
timerDisplay.appendChild(createSpan('5 hours'))
timerDisplay.appendChild(createSpan('16 minutes'))
timerDisplay.appendChild(createSpan('33 seconds'))

function createSpan (text) {
  const span = document.createElement('span')
  span.textContent = text
  return span
}

并使用适当的样式:

p {
  border: solid 5px black;
  background-color: teal;
}
span {
  display: inline-block;
  border-right: solid 5px black;
}

p span:first-child {
  text-align: right;
  width: 150px;
}

span:last-child {
  border-right: none;
}

enter image description here

另一方面,您可以更改 html 代码:

<p id="timer">
  <span class="days">126 days</span>
  <span class="hours"></span>
  <span class="minutes"></span>
  <span class="seconds"></span>
</p>

然后,您可以直接更改 span 元素:

const timerDisplay = document.querySelector("#timer")
const days = timerDisplay.querySelector('.days')
const hours = timerDisplay.querySelector('.hours')
const minutes = timerDisplay.querySelector('.minutes')
const seconds = timerDisplay.querySelector('.seconds')

days.textContent = '126 days'
hours.textContent = '5 hours'
minutes.textContent = '16 minutes'
seconds.textContent = '33 seconds'

并且具有相同的样式:

p {
  border: solid 5px black;
  background-color: teal;
}
span {
  display: inline-block;
  border-right: solid 5px black;
}

p span:first-child {
  text-align: right;
  width: 150px;
}

span:last-child {
  border-right: none;
}

enter image description here

您可以在这个 jsfiddle 中显示示例:jsfiddle example

关于javascript - 如何使用或不使用 javascript 在数字之间添加垂直线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498342/

相关文章:

javascript - 如何制作倒计时器到jquery或js并带有倒计时时间(H :i:s)?

javascript - Chrome 地址栏在移动网站上留下空白

javascript - 是否有用于将字符串编码为 HTML 的内置 jQuery 函数?

javascript - GTM dataLayer .push 创建一个新对象,而不是将其添加到现有 dataLayer

c++ - linux下如何运行ps调试多线程程序?

javascript - Angular ng-class 需要帮助设置

css - 调整一张图片大小时图片移动(CSS 和 HTML)

html - 为什么 Bootstrap 对按钮使用无单位行高,而对边距和填充使用基于像素的行高

php - 在 codeigniter 中调试路由?

css - xHTML/CSS : How to make inner div get 100% width minus another div width