假设我有以下 html:
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...
我想动态设置所有 thinger div 的宽度。我知道我可以这样做:
$(".thinger").css("width",someWidth);
这将导致 html 看起来像这样:
<div class="thinger" style="width: 50px;">...</div>
<div class="thinger" style="width: 50px;">...</div>
<div class="thinger" style="width: 50px;">...</div>
我希望生成的 HTML 看起来像这样:
...
<style>
.thinger {
width: 50px;
}
</style>
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...
我环顾四周,但没有看到用于添加/更新/修改现有 css 类的 jQuery 实用程序。这存在吗?
我知道我可以使用如下方式手动添加它:
var styleElement = document.createElement('style');
styleElement.type = "text/css";
styleElement.innerHTML = ".thinger {width:" + maxWidth + ";}";
document.getElementsByTagName('head')[0].appendChild(styleElement);
但我不想处理浏览器的不一致问题,我想确保我是以“jQuery 方式”做事。有什么理由选择一种方法而不是另一种方法吗?
最佳答案
您可以创建 style
元素并将其附加到 head
,就像在 DOM 中附加任何其他元素一样,但这是浪费时间。
最好的方法是在样式表中设置类规则并将类添加到这些元素中。这保持了更好的关注点分离,这有利于代码重用和以后的维护。
I can't setup the class rule in a stylesheet because I don't know what the width will be prior to runtime.
在这种情况下,您当前使用 css()
的方法是最好的方法。
关于javascript - 使用 jQuery 更新 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325514/