我需要在JavaScript中动态创建一个CSS样式表类,并将其分配给某些HTML元素,如div,table,span,tr等,以及某些控件,如asp:Textbox,Dropdownlist和datalist.
可能吗?
一个样本会很好.
我知道要替换单个样式,代码看起来像这样:
myDOMElement.style.height = '400px';
Run Code Online (Sandbox Code Playgroud)
但是,如果我想一举完全替换整个样式对象,从而加快速度并避免重绘,该怎么办?例如,我想这样做:
//Get the computed style
var computedStyle = window.getComputedStyle(myDOMElement);
//Change some stuff in that CSSStyleDeclaration without rendering
computedStyle.height = '10px';
computedStyle.width = '20px';
computedStyle.whatever = 'something';
//Apply the entirety of computedStyle to the DOM Element, thereby only redrawing once
myDOMElement.style = computedStyle;
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,我的新样式才会被忽略.我该怎么做才能解决这个问题?
我想用JavaScript添加多行CSS.我知道我可以这样做:
document.getElementById(id).style.property=new style
Run Code Online (Sandbox Code Playgroud)
如:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码允许我只添加一个CSS属性.如果想要添加多个属性,如下所示:
#id1 {
color: red;
background-color: beige;
padding-bottom: 2px;
margin: 3px;
}
Run Code Online (Sandbox Code Playgroud)
如何通过不重复添加所有这些:
document.getElementById(id).style.property=new style
Run Code Online (Sandbox Code Playgroud)
....一次又一次.提前致谢 !
是否可以使用存储在 JS 对象中的 CSS 属性来动态设置元素样式?
例如,更改一个简单元素的width和:background<div>
<div id="box"></div>
<button id="btn">click me</button>
Run Code Online (Sandbox Code Playgroud)
盒子最初的样式是:
div {
background: grey;
width: 100px;
height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
单击按钮元素时,该框将重新设置样式,如下所示:
btn.addEventListener('click', () => {
// Code to change box style here...
}
Run Code Online (Sandbox Code Playgroud)
我已经看到了 的使用setAttribute('style', 'some style stuff here');,但是我开始明白,这将简单地替换与该元素关联的所有样式属性,而不是附加/更改 :-( 中定义的属性
我的目标是在 JS 对象中保存 CSS 属性,例如:
const myStyle = {
'background': 'green',
'width': '20px'
}
Run Code Online (Sandbox Code Playgroud)
并将其应用到元素上。
我知道这可以通过将属性保存在另一个名为“.box-transform”之类的 CSS 类中,然后将其添加到元素的 classList 中来完成...但我想通过 JS 来完成此操作。
我最初的尝试是这样的:
btn.addEventListener('click', () => {
for (let [key, val] of …Run Code Online (Sandbox Code Playgroud) 我想设置我的元素的样式:
this.refs.element.style = {
...this.props.style,
background: 'blue',
};
Run Code Online (Sandbox Code Playgroud)
但显然你不能使用一个对象来设置ref的样式.我必须使用CSS样式字符串;分隔prop:values
我知道大多数人都会在渲染功能中设置样式,但出于性能原因,我无法重复渲染.