简体   繁体   English

尝试通过 Id 更改元素 - 不工作

[英]Trying to change element by Id - Not Working

I have tried various things, but I can't get the last three lines to work.我尝试了各种方法,但我无法让最后三行工作。

Any idea's why this will not change the font to red, italics, center align?知道为什么这不会将字体更改为红色、斜体、居中对齐吗?

This is the first day of my course, I have no lecturer to ask, and there is no explanation given.这是我课程的第一天,我没有讲师要问,也没有给出任何解释。

document.bgColor = "blue";
document.fgColor = "white";

var myDemo = document.getElementById("demo");
myDemo.innerHTML = Date();
document.getElementById("demo").fgColor = "red";
myDemo.fontStyle = "italics";
myDemo.textAlign = "center";

The fgColor & bgColor properties are deprecated and not supported in all browsers. fgColor & bgColor属性已弃用,并非所有浏览器都支持。 You could use color & backgroundColor properties to change the color and the background color.您可以使用color & backgroundColor属性来更改颜色和背景颜色。

All the style related properties belongs to the 'style' property of the element.所有与style相关的属性都属于元素的“样式”属性。 We cannot set the css properties directly on the element.我们不能直接在元素上设置 css 属性。 We have to set it on the element style property.我们必须在元素样式属性上设置它。

fgColor & bgColor : These feature are no longer recommended. fgColor & bgColor :不再推荐这些功能。 Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.虽然一些浏览器可能仍然支持它,但它可能已经从相关的 Web 标准中删除,可能正在被删除,或者可能只是为了兼容性目的而保留。 Avoid using it, and update existing code if possible.避免使用它,并尽可能更新现有代码。 Be aware that this feature may cease to work at any time.请注意,此功能可能随时停止工作。

 document.body.style.color = "green" document.body.style.backgroundColor = "black"; function chnageColor() { var myDemo = document.getElementById("demo"); myDemo.innerHTML = Date(); myDemo.style.color = "red"; myDemo.style.fontStyle = "italic"; myDemo.style.textAlign = "center"; }
 <div id="demo"> Some Text </div> <button type="button" onclick="chnageColor()">Change color</button>

You need to use style property of DOM object to access any styling attribute.您需要使用 DOM 对象的style属性来访问任何样式属性。

 var myDemo = document.getElementById("demo"); myDemo.innerHTML = Date(); myDemo.style.fontStyle = "italic"; myDemo.style.textAlign = "center";
 <div id="demo">Testing</div>

You have a typo in italics and also properties you trying to change are set in element.style instead of element itself.您有一个斜体拼写错误,并且您尝试更改的属性也在 element.style 而不是 element 本身中设置。

document.bgColor = "blue";
document.fgColor = "white";

var myDemo = document.getElementById("demo");
console.log(myDemo);
myDemo.innerHTML = Date();
document.getElementById("demo").style.color = "red";
myDemo.style.fontStyle = "italic";
myDemo.style.textAlign = "center";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM