简体   繁体   English

为什么我不能直接设置“样式”

[英]Why can't I set “style” directly

Let's suppose I have a <div> . 假设我有一个<div> I set its style to color:red . 我将其style设置为color:red

<div style="color:red">text</div>

Why can't I set style through javascript like so: 为什么我不能像这样通过javascript设置style

document.getElementsByTagName("div")[0].style="color:blue";

But only can set property of style: 但只能设置样式的属性:

document.getElementsByTagName("div")[0].style.color="blue";
document.getElementsByTagName("div")[0].style.cssText = "color: blue;"

src: http//www.w3schools.com/jsref/prop_style_csstext.asp

This is dom model. 这是dom模型。 What js debug tool do you use? 您使用哪种js调试工具? Run this in your browser console: 在浏览器控制台中运行以下命令:

document.getElementsByTagName("div")[0].style

This will be result: 结果将是:

在此处输入图片说明

So, this command returned object. 因此,此命令返回了对象。 By this: 这样:

document.getElementsByTagName("div")[0].style="color:blue";

You redefining object. 您重新定义对象。 It is not correct at all. 这根本不正确。

That's it and you can't do anything with it. 就这样,您什么也做不了。

If you want to have a tool to manage css properties better you can use jQuery : prop() function 如果您想拥有一个更好地管理CSS属性的工具,则可以使用jQueryprop()函数

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

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