如何创建的一致好评CSS类
问题描述:
可能重复:
How to dynamically create CSS class in JavaScript and apply?如何创建的一致好评CSS类
我想创建取决于什么用户指定的文本框的宽度CSS类。我知道我可以使用内联样式来做到这一点,但我想避免它,因为有很多属性需要处理。在这个问题中,“宽度”仅仅是一个例子。
对于例如:如果用户指定的宽度, “20”,那么我想 -
.w20 {width:20px}
如果用户指定21那么我想
.w21 {width:21px}
等等...
谢谢。
答
您可以使用document.stylesheets
动态添加css规则直接到您的样式表。
styleSheet = document.styleSheets[0];
// check for undefined could make sense here
styleSheet.addRule(selector, style);
或创建一个新的风格元素
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.class { rules }';
document.getElementsByTagName('head')[0].appendChild(style);
答
你可以尝试使用document.stylesheets
动态地添加到CSS样式表。
styleSheet = document.styleSheets[0];
styleSheet.addRule(selector, style);
你也可以使用内联样式(id推荐这种方法)。
您可以像这样使用JavaScript更改元素的宽度。
elem.style.width = "100px";
而且使用jQuery
$("#selector").css("width", "100px");
+0
谢谢,但我知道内联方法,我提到的问题是我不想这样做。 – Ashwin 2012-07-18 07:53:29
你回答完美。 – Ashwin 2012-07-18 07:48:00
不客气;) – Christoph 2012-07-18 08:03:49