javascript - 使用 jQuery 更新 CSS 属性

标签 javascript jquery css

假设我有以下 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/

相关文章:

javascript - AngularJS - 具有多个实例的 Controller 的表单验证

javascript - 内容脚本未执行

jquery - 使用 jquery BlockUI 插件 block 表行

css - 避免从 HTML 中的部分文本复制避免不必要的内容?

javascript - 在 Angular2 组件中使用 Bootstrap 导航

html - Chrome 中的 Arial 窄字体问题

javascript - 如何在react中编写多重导出?

javascript - 对点路径进行动画处理,一个点接一个点

javascript - jQuery:悬停菜单 - 代码清理 - 保持菜单打开

javascript - 未捕获的异常 : out of memory in Ajax Process