使用 JavaScript 动态应用 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35630641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:02:37  来源:igfitidea点击:

Apply CSS dynamically with JavaScript

javascriptcssencapsulationstylingweb-component

提问by Juan Carlos Coto

What is a good way to apply styling dynamically (i.e. the value of styles are created at runtime) to HTML elements with JavaScript?

使用 JavaScript 动态地将样式(即样式的值在运行时创建)应用于 HTML 元素的好方法是什么?

I'm looking for a way to package a JavaScript widget (JS, CSS and markup) in a single component (basically, an object). The idea would be for the component to encapsulate styling (so users have a nice API to modify it instead of a more tightly coupled approach of modifying the CSS directly and having changes applied indirectly). The problem is that a single API call might imply changes to several styling elements.

我正在寻找一种将 JavaScript 小部件(JS、CSS 和标记)打包到单个组件(基本上是一个对象)中的方法。这个想法是让组件封装样式(因此用户有一个很好的 API 来修改它,而不是直接修改 CSS 并间接应用更改的更紧密耦合的方法)。问题是单个 API 调用可能意味着更改多个样式元素。

The way I would do it is to construct the CSS and set thestyleatrribute to the proper elements (most likely using the ID to avoid applying changes to other areas of the markup). Is this a good solution? Is there a better way to do it?

我这样做的方法是构造 CSS 并将属性设置为style适当的元素(最有可能使用 ID 来避免将更改应用于标记的其他区域)。这是一个很好的解决方案吗?有没有更好的方法来做到这一点?

回答by kerwan

Using Jquery

使用 Jquery

Use the css() function to apply style to existing elements where you pass an object containing styles :

使用 css() 函数将样式应用于传递包含样式的对象的现有元素:

var styles = {
  backgroundColor : "#ddd",
  fontWeight: ""
};
$("#myId").css(styles);

You can also apply one style at the time with :

您还可以同时应用一种样式:

$("#myId").css("border-color", "#FFFFFF");

Vanilla JS :

香草JS:

var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");

With Css :

使用 CSS :

You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.

您还可以使用单独的 css 文件,其中包含类中所需的不同样式,并根据上下文将这些类添加或删除到元素中。

in your css file you can have classes like

在你的 css 文件中,你可以有这样的类

.myClass {
    background-color: red;
}

.myOtherClass {
    background-color: blue;
}

Again using jquery, to add or remove a class to an element, you can use

再次使用 jquery,向元素添加或删除类,您可以使用

$("#myDiv").addClass('myClass');

or

或者

$("#myDiv").removeClass('myClass');

I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.

我认为这是一种更简洁的方式,因为它将您的风格与您的逻辑分开。但是,如果您的 css 值取决于服务器返回的值,则此解决方案可能难以应用。

回答by Dean Meehan

The way I would do it is to construct the CSS and set the style attribute to the proper elements. For example:

我这样做的方法是构造 CSS 并将样式属性设置为适当的元素。例如:

var div = document.createElement('div');
div.setAttribute("style", "color: blue, margin-top:5px");
document.body.appendChild(div);

This code will create a new div element with the style color: blue, margin-top:5pxand append it to the page.

此代码将使用该样式创建一个新的 div 元素color: blue, margin-top:5px并将其附加到页面。

回答by Rahul kalivaradarajalu

Using Vanilla JSyou could do something like this.

使用Vanilla JS你可以做这样的事情。

If you want to add a CSS classnamed animateto an element with Id circle, do it like this.

如果您想将名为animateCSS 类添加到 Id circle元素,请按以下方式操作。

var circle = document.getElementById("circle");
circle.classList.add('animate');

You can remove the class like this.

您可以像这样删除类。

circle.classList.remove('animate');

回答by Matovu Ronald

Since you have also asked if there is a better way and you building a component, a better way i would recommend is for you to build such a component with frontend javascript framework because they make dynamically styles very easy out of the box take an example of Vuejs, Reactjs

由于您还询问是否有更好的方法并且您构建了一个组件,因此我建议您使用前端 javascript 框架构建这样一个组件,因为它们使动态样式非常容易开箱即用,举个例子Vuejs、Reactjs

`      
import React, {Component} from 'react'
import styled from 'styled-jss'
const Circle = styled('div')({
  position: 'absolute',
  width: 50,
  height: 50,
  borderRadius: '50%',
  background: (props) => (
    /* Generates a random or based on props color */
  ),
  transform: (props) => (
    /* Generates a random or based on props transform for  positioning */
  )
})
class Demo extends Component {
  componentDidMount() {
    this.tick()
  }
  tick = () => {
    requestAnimationFrame(() => {
      this.setState({/* Some new state */}, this.tick)
    })
  }
  render() {
    return (
      <div>
        {[...Array(amount)].map(() => <Circle />)}
      </div>
    )
  }
}
`

回答by Chris Dutrow

I could be misinterpreting your question, but it sounds like you are asking for a simple architectural pattern. You want something that makes it easier for someone who is using your widget to change it to their specifications?

我可能会误解你的问题,但听起来你是在要求一个简单的架构模式。您想要一些让使用您的小部件的人更容易将其更改为他们的规格的东西吗?

If this is the case, then I do not know of any special pattern to do this without using CSS.

如果是这种情况,那么我不知道有什么特殊的模式可以在不使用 CSS 的情况下做到这一点。

I can tell you that the "widgets" that I have found easiest to use do have separate CSS files. I have found it fairly straightforward to modify them to my needs. I think this is because the structure of using CSS with HTML and Javascript is already a nice, simple pattern. I don't know of there is anything better, especially considering that people are already very familiar with the HTML/CSS relationship.

我可以告诉你,我发现最容易使用的“小部件”确实有单独的 CSS 文件。我发现根据我的需要修改它们相当简单。我认为这是因为将 CSS 与 HTML 和 Javascript 结合使用的结构已经是一个不错的简单模式。我不知道还有什么更好的,特别是考虑到人们已经非常熟悉 HTML/CSS 关系。