使用JavaScript更改css类模型
changing css class model using JavaScript
使用JavaScript更改css类模型有可能吗?
伪代码:
function updateClass(className, newData) {
cssInterface.alterClass(className, newData);
}
className是应该更改的类的名称(如".footer"),newData是新的类内容(如border:"1px solid pink;")。
实际上,目标只是为了节省空间:我正在使用CSS3动画,因此更改受其类影响的元素的一个属性将终止其动画-(在我的情况下)字体大小将不再更改。使用不同的类将需要为所有受影响的元素创建一组全新的类,我希望避免这种情况。
我没有通过搜索更改
element.className = "foo";
或
element.style.fontSize = "15pt";
谢谢你们的帮助,伙计们:)
下面是我的函数。。。
function changeCSS(typeAndClass, newRule, newValue) // modify the site CSS (if requred during scaling for smaller screen sizes)
{
var thisCSS=document.styleSheets[0] // get the CSS for the site as an array
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules // work out if the browser uses cssRules or not
for (i=0; i<ruleSearch.length; i++) // for every element in the CSS array
{
if(ruleSearch[i].selectorText==typeAndClass) // find the element that matches the type and class we are looking for
{
var target=ruleSearch[i] // create a variable to hold the specific CSS element
var typeExists = 1;
break; // and stop the loop
}
}
if (typeExists)
{
target.style[newRule] = newValue; // modify the desired class (typeAndClass) element (newRule) with its new value (newValue).
}
else
{
alert(typeAndClass + " does not exist.");
}
}
使用(示例)调用
changeCSS("div.headerfixed","-moz-transform-origin", "100% 0%");
希望这能有所帮助。
请在此处查看我的答案。回答你的问题:是的,这是可能的。
@CSS3:我在我的一个html5实验中尝试了完全相同的方法。我创建了一个额外的<style>
元素,并将其contentText
更改为我需要的CSS类定义。当然,更改cssRule对象会更干净:-)
据我所知,CSS对象模型不能很容易地告诉你是否已经有了特定类的现有样式规则,但你可以很容易地为该类附加一个新规则,它将覆盖该样式以前的任何声明。
我发现了一个创建动态样式表的例子。
你应该看看dojo,它有一些不错的功能,你可以做到这一点。。
require(["dojo/dom-class"], function(domClass){
// Add a class to some node:
domClass.add("someNode", "anewClass");
});
http://dojotoolkit.org/reference-guide/1.7/dojo/addClass.html
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- CSS-如何定位内容数据标题
- 窗口大小html css
- 如果文本字段为空,则使用JavaScript应用CSS样式
- 动画.CSS重播
- 有没有一种方法可以防止img get请求使用css或js发生
- CSS表格:从列平移到整个表格宽度
- CKEditor-我在editor.css中的风格是't
- 单击更改图标并通过javascript添加一个css类
- 将CSS应用于printWindow.print();在Javascript中
- 为集合分配大量的模型弹药
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- 如何使用backbone.js从集合中获取模型名称
- 如何更改与Backbone集合中的模型相关联的几个元素的css属性
- Ember.js为特定的模型id添加css类
- 单击轨道按钮以永久更改数据模型和 css
- 使用JavaScript更改css类模型
- AngularJS在点击元素时更新模型,并切换CSS类
- CSS 3 flex模型宽度jQuery
- 灵活css框模型的一些问题