用jquery添加新的CSS规则的最佳方法? [英] Best way to add new css rules with jquery?
问题描述
我在网页上动态插入一些html(在我检测到用户的事件后)。这个html需要一些CSS样式,我想知道什么是最干净的方式来做到这一点,使用jQuery。我不是网站开发者,所以我不能添加这些规则到原来的CSS。
I am dynamically inserting some html on a web page (after I detect an event from the user). This html needs some css styling and I am wondering what is the cleanest way to do it, using jQuery. I am not the website developer, so I can't add those rules to the original css.
假设我已经插入一些html没有样式,包括 formElement
类。我可以在我的文档中写入一个新的< style>
块,例如:
Assume I have already inserted some html without styling, including a formElement
class. I can write in my document a new <style>
block, for instance:
my_html = '<style type="text/css">';
my_html += ' .formElement {';
my_html += ' display: block;';
my_html += ' width: 240px;';
my_html += ' position: relative;';
my_html += ' padding: 4px 0;';
my_html += ' }';
my_html += '</style>';
my_html = $(my_html);
$('body').prepend(my_html);
或者,我可以使用 css
方法:
Or, I can use the css
method:
$('.formElement').css({
'display': 'block',
'width': '240px',
'position': 'relative',
'padding': '4px 0'
});
哪种解决方案是最好的/最干净的?
Which solution is the best/cleanest?
EDIT:
由于我无法在CSS中直接添加规则,所以我将坚持使用 css
jQuery的方法。一些其他相关问题也提供解决方案:
As I can't directly add the rules in the CSS, I will stick with the css
method of jQuery. Some other related questions provide solutions as well:
- jQuery create CSS rule / class @ runtime
- Changing CSS Rules using JavaScript or jQuery
我不能真正使用jQuery插件,但如果可以,我一定会使用 jQuery.Rule
I can't really use jQuery plugins, but if I could, I would certainly use jQuery.Rule
感谢大家的宝贵帮助。
推荐答案
老实说,最好的方法可能不是。如果我不得不选择一个,jquery css
方法将是我的选择,只是因为它更干净,但是,考虑这个选择更好的性能和更清晰的代码:
Honestly, the best way may be neither. If I had to pick one, the jquery css
method would be my choice, just because it's cleaner, however, consider this alternative for better performance and cleaner looking code:
创建CSS类以在需要时附加到元素。例如:
Create CSS classes to append to your elements when needed. For example:
.formElementAlpha {
width:240px;
padding:4px 0;
}
.formElementBravo {
width:400px;
height:50px;
padding:20px 0;
line-height:50px;
font-size:30px;
}
然后,使用jquery,当你需要它:
then, with jquery, when you need it:
$('.formElement').addClass('formElementAlpha');
或
$('.formElement[name="bigUsernameInput"]').addClass('formElementBravo');
我会保留jQuery css
您需要根据某种用户交互或其他需要使用JavaScript变量值来确定所应用的样式的动态事件来修改特定元素的实例。因为它看起来像你已经知道你想要的样式,让CSS做的工作。
I would reserver the jQuery css
method for instances where you need to modify a specific element based on some sort of user interaction or other dynamic event that requires you to use the value of your JavaScript variables to determine the styles you are applying. Since it looks like you already know how you want to style them, let CSS do the work.
这篇关于用jquery添加新的CSS规则的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!