的CSS
div.online:last-child {
color:green;
}
div.offline:last-child {
color:green;
}
JavaScipt
var x=navigator.onLine;
var div = document.createElement("div");
if (x==false) {
var divContent = document.createTextNode("sorry, you're offline");
divContent.className="offline:last-child";
div.appendChild(divContent);
var k = document.body.appendChild(div);
} else {
var divContent = document.createTextNode("you are online");
divContent.className="online:last-child";
div.appendChild(divContent);
var k = document.body.appendChild(div);
}
在这里,我使用伪类.className
更改最后一个单词的样式last-child
(因此只有离线和在线的样式)。我猜我的 js 代码中的类命名存在问题。在我采用这种方法之前,我使用过setAttribute
,但我不知道如何使用它来使用伪类。我应该使用什么类名(和/或代码)?