如何在CSS中将time
变量的内容显示为content
属性?
JavaScript:
function clock(){
var d = new Date();
var hour = d.getHours();
var min = d.getMinutes();
var time = hour + ":" + min;
}
CSS:
.screen{
position: absolute;
height: 75%;
width: 75%;
background: #98E8EE;
top: 11.5%;
left: 12.5%;
}
.screen::after{
color: #F9F5F4;
font-size: 40px;
content: ;
font-family: Arial;
margin-left: 36.5px;
top: 20px;
position: relative
}
我不确定这是否是实现您想要做的最好的方法,因为您还可以使用容器元素并直接更改其内容:
const screenContentElement = document.getElementById('screen__content');
function pad(value) {
const str = value + '';
return str.length === 2 ? str : '0' + str;
}
function clock(){
var d = new Date();
return pad(d.getHours())
+ ':' + pad(d.getMinutes())
+ ':' + pad(d.getSeconds());
}
setInterval(() => {
screenContentElement.innerText = clock();
}, 1000);
#screen {
font-family: Arial, sans-serif;
position: relative;
height: 100%;
width: 100%;
background: #98E8EE;
text-align: center;
padding: 2rem 0;
}
#screen__content {
color: #F9F5F4;
font-size: 40px;
}
<div id="screen" class="screen">
<span id="screen__content"></span>
</div>
但是,关于您提供的代码,要动态更改伪元素中的content
属性值,CSS
可以将attr()
CSS函数与data-*
attribute一起使用:
const screenElement = document.getElementById('screen');
function pad(value) {
const str = value + '';
return str.length === 2 ? str : '0' + str;
}
function clock(){
var d = new Date();
return pad(d.getHours())
+ ':' + pad(d.getMinutes())
+ ':' + pad(d.getSeconds());
}
setInterval(() => {
screenElement.dataset.time = clock();
}, 1000);
#screen {
font-family: Arial, sans-serif;
position: relative;
height: 100%;
width: 100%;
background: #98E8EE;
text-align: center;
padding: 2rem 0;
}
#screen::before {
color: #F9F5F4;
font-size: 40px;
content: attr(data-time);
}
<div id="screen"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句