我必须用if语句创建一个页面,并需要一种使用if语句更改字体颜色的方法。有标签可以用来改变背景色吗?
JavaScript:
document.write("<H1>Some Flow of Control</H1>");
var random = Math.floor(Math.random() > 0.5);
document.write("<P>Signed</P>");
if (random) {
document.write("<img src='bonw.gif' id='myImg'/>")
} else {
document.write("<img src='wonb.gif' id='myImg'/>")
}
if (random) {
document.body.style.backgroundColor = ("white");
} else {
document.body.style.backgroundColor = ("black");
}
发布于 2014-11-03 13:28:23
它是:
document.body.style.backgroundColor="red";而不是:
document.body.style.backgroundColor = ("black");没有()。
请参阅更多这里
发布于 2014-11-03 13:27:29
只需删除颜色名称中的括号
if(random){
document.body.style.backgroundColor = "white";
}else{
document.body.style.backgroundColor = "black";
}发布于 2014-11-03 14:13:12
创建真实元素,而不是使用document.write。
基于小提琴的演示
JavaScript:
// This function will let you create elements easily.
function createElem(args = {}) {
var elem = document.createElement(args.tag);
var elemText = document.createTextNode(args.text);
elem.appendChild(elemText);
elem.src = args.src;
elem.id = args.id;
document.body.appendChild(elem);
}
createElem({
tag: 'h1',
text: 'Some Flow of Control'
});
createElem({
tag: 'p',
text: 'Signed'
});
var random = Math.floor(Math.random() > 0.5);
if (random) {
createElem({
tag: 'img',
src: 'http://s25.postimg.org/e2wx0t4p7/chrome.png',
id: 'myImg'
});
document.body.style.backgroundColor = 'white';
} else {
createElem({
tag: 'img',
src: 'http://s25.postimg.org/kbo7u96hb/safari_1127142725.png',
id: 'myImg'
});
document.body.style.backgroundColor = 'black'; // background color
document.body.style.color = 'white'; // font color
}https://stackoverflow.com/questions/26715267
复制相似问题