简体   繁体   English

在 JavaScript 中设置 CSS 属性?

[英]Set CSS property in JavaScript?

I've created the following...我创建了以下...

var menu = document.createElement('select');

How would I now set CSS attributes eg width: 100px ?我现在如何设置 CSS 属性,例如width: 100px

Use element.style :使用element.style

var element = document.createElement('select');
element.style.width = "100px";

Just set the style :只需设置style

var menu = document.createElement("select");
menu.style.width = "100px";

Or if you like, you can use jQuery :或者,如果您愿意,可以使用jQuery

$(menu).css("width", "100px");

For most styles do this:对于大多数样式,请执行以下操作:

var obj = document.createElement('select');
obj.style.width= "100px";

For styles that have hyphens in the name do this instead:对于名称中包含连字符的样式,请改为执行以下操作:

var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"

使用 vanilla JavaScript 这实际上非常简单:

menu.style.width = "100px";

All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS.所有答案都正确地告诉您如何执行您所要求的操作,但我建议使用 JavaScript 在元素上设置一个类并使用 CSS 为其设置样式。 That way you are keeping the correct separation between behaviour and style.这样你就可以在行为和风格之间保持正确的分离。

Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.想象一下,如果您让一位设计师重新设计网站的样式……他们应该能够完全使用 CSS 工作,而无需使用您的 JavaScript。

In prototype I would do:在原型中,我会这样做:

$(newElement).addClassName('blah')

Just for people who want to do the same thing in 2018只为那些想在 2018 年做同样事情的人

You can assign a CSS custom property to your element (through CSS or JS) and change it:您可以为您的元素分配一个 CSS 自定义属性(通过 CSS 或 JS)并更改它:

Assigment through CSS:通过 CSS 赋值:

element {
  --element-width: 300px;

  width: var(--element-width, 100%);
}

Assignment through JS通过 JS 赋值

ELEMENT.style.setProperty('--element-width', NEW_VALUE);

Get property value through JS通过JS获取属性值

ELEMENT.style.getPropertyValue('--element-width');

Here useful links:这里有用的链接:

if you want to add a global property, you can use:如果要添加全局属性,可以使用:

    var styleEl = document.createElement('style'), styleSheet;
            document.head.appendChild(styleEl);
            styleSheet = styleEl.sheet;
            styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);

When debugging, I like to be able to add a bunch of css attributes in one line:调试时,我喜欢能够在一行中添加一堆css属性:

menu.style.cssText = 'width: 100px';

Getting used to this style you can add a bunch of css in one line like so:习惯这种风格后,您可以在一行中添加一堆 css,如下所示:

menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';
<h1>Silence and Smile</h1>
<input  type="button"  value="Show Red"   onclick="document.getElementById('h1').style.color='Red'"/>
<input  type="button"  value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>
<body>
  <h1 id="h1">Silence and Smile</h1><br />
  <h3 id="h3">Silence and Smile</h3>

  <script type="text/javascript">
    document.getElementById("h1").style.color = "Red";
    document.getElementById("h1").style.background = "Green";
    document.getElementById("h3").style.fontSize = "larger" ; 
    document.getElementById("h3").style.fontFamily = "Arial";
  </script>
</body>

This works well with most CSS properties if there are no hyphens in them.如果其中没有连字符,这适用于大多数 CSS 属性。

var element = document.createElement('select');
element.style.width = "100px";

For properties with hyphens in them like max-width , you should convert the sausage-case to camelCase对于像max-width这样带有连字符的属性,您应该将sausage-case转换为camelCase

var element = document.createElement('select');
element.style.maxWidth = "100px";

It is important to understand that the code bellow does not change the stylesheet, but instead changes the DOM:重要的是要了解以下代码不会更改样式表,而是更改 DOM:

document.getElementById("p2").style.color = "blue";

The DOM stores a computed value of the stylesheet element properties, and when you dynamically change an elements style using Javascript you are changing the DOM. DOM 存储样式表元素属性的计算值,当您使用 Javascript 动态更改元素样式时,您正在更改 DOM。 This is important to note, and understand because the way you write your code can affect your dynamics.需要注意并理解这一点很重要,因为您编写代码的方式会影响您的动态。 If you try to obtain values that were not written directly into the element itself, like so...如果您尝试获取未直接写入元素本身的值,就像这样......

let elem = document.getElementById('some-element');
let propertyValue = elem.style['some-property'];

...you will return an undefined value that will be stored in the code example's 'propertyValue' variable. ...您将返回一个未定义的值,该值将存储在代码示例的 'propertyValue' 变量中。 If you are working with getting and setting properties that were written inside a CSS style-sheet and you want a SINGLE FUNCTION that gets, as well as sets style-property-values in this situation, which is a very common situation to be in, then you have got to use JQuery.如果您正在处理编写在 CSS 样式表中的获取和设置属性,并且您想要一个在这种情况下获取和设置样式属性值的单一功能,这是一种非常常见的情况,那么你必须使用JQuery。

$(selector).css(property,value)

The only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery.唯一的缺点是您必须了解 JQuery,但老实说,这是每个 Javascript 开发人员都应该学习 JQuery 的众多充分理由之一。 If you want to get a CSS property that was computed from a style-sheet in pure JavaScript then you need to use.如果您想获得从纯 JavaScript 中的样式表计算出的 CSS 属性,那么您需要使用。

function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

The downside to this method is that the getComputedValue method only gets, it does not set.这种方法的缺点是 getComputedValue 方法只能获取,不能设置。 Mozilla's Take on Computed Values This link goes more into depth about what I have addressed here. Mozilla 对计算值的看法 此链接更深入地介绍了我在此处讨论的内容。 Hope This Helps Someone!!!希望这对某人有帮助!!!

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

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