如何在span或粗体标记中包装javascript变量?

时间:2014-05-20 11:47:49

标签: javascript html css

我已经获得了一些JavaScript,可以创建一个数字时钟进入网页。这是完美的工作,但是我尝试修改它以在span或粗体标签中包装am / pm后缀(或此代码中的diem),以便我可以在CSS中将其设置为与其余时间不同的样式。

我确信对于那些知道他们正在做什么的人来说这真的很简单,但我真的很挣扎。任何帮助将不胜感激,JavaScript如下:

function renderTime() {
    var currentTime = new Date();
    var diem = "AM";
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();
    setTimeout('renderTime()',1000);
    if (h == 0) {
        h = 12;
    } else if (h > 12) { 
        h = h - 12;
        diem="PM";
    }

    if (m < 10) {
        m = "0" + m;
    }
    if (s < 10) {
        s = "0" + s;
    }
    var myClock = document.getElementById('clockDisplay');
    myClock.textContent = h + ":" + m + " " + diem;
    myClock.innerText = h + ":" + m + " " + diem;
    var diem = document.createElement('span');
}
renderTime();

3 个答案:

答案 0 :(得分:4)

您有几个选择:

使用innerHTML代替innerText。这允许您将HTML标记插入到字符串中:

myClock.innerHTML = h + ":" + m + " <span>" + diem + "</span>;

使用appendChild并忽略innerText末尾的diem

myClock.innerText = h + ":" + m + " ";
var diemSpan = document.createElement('span');
diemSpan.innerText = diem;
myClock.appendChild(diemSpan);

最后,您可以在标记中添加clockDisplaydiem范围并适当地访问它们:

<强>标记:

<div id="clockDisplay">
    <span id="clockDisplay-time"></span>
    <span id="clockDisplay-suffix"></span>
</div>

<强>脚本:

document.getElementById("clockDisplay-time").innerText = h + ":" + m;
document.getElementById("clockDisplay-suffix").innerText = diem;

答案 1 :(得分:1)

试试这个:

var myClock = document.getElementById('clockDisplay');
var suffix = document.createElement('span');
suffix.innerText = diem;
myClock.innerText = h + ":" + m + " ";
myClock.append(suffix);

或者,如果你想提高效率(纯DOM操作):

var myClock = document.getElementById('clockDisplay');
var suffix = document.createElement('span');
suffix.append(document.createTextNode(diem));
myClock.append(document.createTextNode(h + ":" + m + " "));
myClock.append(suffix);

答案 2 :(得分:0)

Here's一个JSfiddle给你。它应该按照你想要的方式工作。

解决方案是为时间创建不同的跨度和“diem”,如下所示:

<强> HTML:

<p><span id="time"><!-- time will go here --></span><span id="diem"><!-- "diem" will go here --></span></p>

然后单独访问它们。您也可以在CSS中对它们进行不同的样式设置,如下所示:

<强> CSS:

span#diem {
    font-weight: bold;
    // your styles
}

<强> JS:

window.onload = function() {
    renderTime();
}

function renderTime() {
    // Insert time calculations here

    var time_span = document.getElementById('time');
    time_span.innerText = h + ":" + m;

    var diem_span = document.getElementById("diem");
    diem_span.innerText = " " + diem;    
}

有关renderTime()中的完整代码,请参阅Fiddle