我创建了一个计时器来倒计时到特定日期,它显示没有问题。但是这一次,我想添加垂直线来分隔它们。我试图通过 borderLeft
和 height
来查看垂直线,但没有成功。不过,我确实看到了 1px solid
边框。下图说明了我想在浏览器中看到的内容。
我还希望文字(天、小时、分钟、秒)显示在数字下方。根据图片,它直接出现在他们旁边。我尝试使用 \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;
}
另一方面,您可以更改 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;
}
您可以在这个 jsfiddle 中显示示例:jsfiddle example
关于javascript - 如何使用或不使用 javascript 在数字之间添加垂直线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498342/