使用 JavaScript / jQuery 动态修改 CSS 类属性值
我遇到了一个独特的情况,到目前为止我还无法找到解决方案:动态为 CSS 样式分配值。我知道如何使用 jQuery 为元素分配宽度、高度等,但我想做的实际上是更改样式表中定义的值,以便可以将动态创建的值分配给多个元素。
我正在构建的是占据整个视口的图像幻灯片,在调整大小时重新计算图像的宽度、高度和左侧属性,以便图像始终居中,优先考虑宽度而不是高度,除非视口比实际高度高宽(调整大小不会重新加载页面,只是触发调整图像大小的函数)。
我已经成功地让它在一张图像上工作,现在我正在尝试确定将这些属性值分配给幻灯片中的所有图像的最佳方法,而不必为每个图像单独指定这三件事。
我的问题:
类中属性的值可以动态修改吗?我确信答案就在那里,我可能只是在搜索中没有使用正确的术语。希望我很好地描述了问题。 TIA。
I've run into a unique situation that I have so far been unable to find a solution for: dynamically assigning a value to a CSS style. I know how to use jQuery to assign width, height, etc. to an element, but what I'm trying to do is actually change the value defined in the stylesheet so that the dynamically-created value can be assigned to multiple elements.
What I'm building is a slideshow of images that occupy the full viewport, recalculating the image's width, height, and left properties on resize so that the image is always centered, favors width over height, except when the viewport is taller than it is wide (resizing does not reload the page, just fires a function to resize the image).
I have successfully been able to get it to work on one image, and now I'm trying to determine the best way to assign those property values to all images in the slideshow without having to specify those three things individually for every image.
My Question:
Can the values of properties in a class be modified on the fly? I'm sure the answer is out there, I'm probably just not using the correct terminology in my searches. Hope I did a good job of describing the problem. TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
与这里的一些答案相反,使用 Javascript 编辑样式表本身不仅是可能的,而且性能更高。简单地执行
$('.myclass').css('color: red')
最终将循环遍历与选择器匹配的每个项目并单独设置样式属性。这确实效率低下,如果你有数百个元素,就会导致问题。更改项目的类是一个更好的主意,但您仍然会遇到同样的问题,因为您要更改 N 个项目的属性,这可能是一个很大的数字。更好的解决方案可能是更改单个父项或少量父项的类,然后使用 css 中的“级联”命中目标项。这适用于大多数情况,但不是全部。
有时你需要将很多项目的 CSS 更改为动态的,或者你没有什么好办法通过打击少数父母来做到这一点。更改样式表本身,或添加一个小的新样式表来覆盖现有 CSS 是更改项目显示的一种极其有效的方法。您只需在一处与 DOM 交互,浏览器就可以非常有效地处理部署这些更改。
jss 是一个库,可以帮助您更轻松地直接从 JavaScript 编辑样式表。
Contrary to some of the answers here, editing the stylesheet itself with Javascript is not only possible, but higher performance. Simply doing
$('.myclass').css('color: red')
will end up looping through every item matching the selector and individually setting the style attribute. This is really inefficient and if you have hundreds of elements, it's going to cause problems.Changing classes on the items is a better idea, but you still suffer from the same problem in that you're changing an attribute on N items, which could be a large number. A better solution might be to change the class on one single parent item or a small number of parents and then hit the target items using the "Cascade" in css. This serves in most situations, but not all.
Sometimes you need to change the CSS of a lot of items to something dynamic, or there's no good way for you to do so by hitting a small number of parents. Changing the stylesheet itself, or adding a small new one to override the existing css is an extremely efficient way to change the display of items. You're only interacting with the DOM in one spot and the browser can handle deploying those changes really efficiently.
jss is one library that helps make it easier to directly edit the stylesheet from javascript.
演示,IE demo
您可以使用以下函数:
功能:
setStyle
后会创建一个样式表,因此如果您不调用它,它将不会创建任何样式表。setStyle
调用。示例
浏览器支持
至少,它适用于 IE9、FF3、Chrome 1、Safari 4、Opera 10.5。
还有一个 IE 版本,它可以在现代浏览器和旧版本浏览器上运行IE!
(适用于 IE8 和 IE7,但可能会使 IE6 崩溃)。
Demo, IE demo
You could use the following function:
Features:
setStyle
, so if you don't call it, it won't create any stylesheet.setStyle
Example
Browser support
At least, it works on IE9, FF3, Chrome 1, Safari 4, Opera 10.5.
There's also an IE version which works both on modern browsers and old versions of IE!
(Works on IE8 and IE7, but can crash IE6).
好问题。这里的很多答案都有一个与您所问的直接矛盾的解决方案
jQuery
.css
样式元素内联:它不会改变物理 CSS 规则!如果你想这样做,我建议使用普通的 JavaScript 解决方案:这样,你可以设置样式表 css 规则,而不是附加内联样式。
希望这有帮助!
Nice question. A lot of the answers here had a solution directly contradicting what you were asking
jQuery
.css
styles elements inline: it doesn't change the physical CSS rule! If you want to do this, I would suggest using a vanilla JavaScript solution:This way, you're setting the stylesheet css rule, not appending an inline style.
Hope this helps!
就像 @benvie 所说,更改样式表比使用 jQuery.css (它将循环遍历集合中的所有元素)更有效。同样重要的是,不要在每次调用函数时都向头部添加新样式,因为这会造成内存泄漏,并且浏览器必须单独应用数千条 CSS 规则。我会做这样的事情:
这个解决方案将通过每次调整大小时仅修改一次 DOM 来更改您的样式。请注意,为了有效地缩小和压缩 js,您可能不想漂亮地打印 css,但为了清楚起见,我这样做了。
Like @benvie said, its more efficient to change a style sheet rather than using jQuery.css (which will loop through all of the elements in the set). It is also important not to add a new style to the head every time the function is called because it will create a memory leak and thousands of CSS rules that have to be individually applied by the browser. I would do something like this:
This solution will change your styles by modifying the DOM only once per resize. Note that for effective js minification and compression, you probably don't want to pretty-print the css, but I did for clarity.
使用 jquery 在
中添加样式覆盖:
Use jquery to add a style override in the
<head>
:我有一个更改特定 CSS 类中的值的解决方案。但只有当你将 CSS 保留在标签中时它才有效。如果您只是保留外部文件(例如)到 CSS 的链接。
这个解决方案行不通。
例如,如果您的 css 如下所示:
您可以使用 JS/jQuery 更改标签的值。
我写了一个函数,也许它不是最好的,但它可以工作。如果您愿意,您可以改进它。
然后只需将标签变量更改为样式标签 id 并执行:
这与 $('.foo').css('height','50px'); 之间的区别是,当您使用 jQuery 的 css 方法执行此操作时,所有具有 .foo 类的元素将在 DOM 中具有可见的 style='height:50px' 。如果你按照我的方式做,元素不会被改变,你唯一会看到的是 class='foo'
优点
缺点强>
希望它能有所帮助。
I've got a solution for changing a value in specific CSS class. But it only works if you keep your CSS in the tag. If you just keep a link to your CSS from external files ex.
this solution won't work.
If your css looks like this for example:
You can change a value of the tag using JS/jQuery.
I've written a function, perhaps it's not the best one but it works. You can improve it if you want.
Then just change the tag variable into your style tag id and exegute:
The difference between this and $('.foo').css('height','50px'); is that when you do it with css method of jQuery, all elements that have .foo class will have visible style='height:50px' in DOM. If you do it my way, elements are untouched and the only thing youll see is class='foo'
Advantages
Disadvantages
Hope it helps anyhow.
动态修改 CSS 类中的 CSS 属性值的方法是在 CSS 类属性值中使用 CSS 变量,然后使用 JavaScript 和 DOM 来更改 CSS 变量。最终结果是,当设置新 CSS 变量值的代码运行时,设备屏幕上的样式将立即更改。因此,代码更改了 CSS 变量,并且 CSS 变量用于 CSS 类设置。请注意,CSS 类名和 JavaScript 类是两个不同的东西。
CSS - 样式化
JavaScript 和 DOM
还可以使用
matchMedia()
方法运行一个函数来响应媒体查询(设备视口的变化 - 例如设备屏幕的宽度)。The way to dynamically modify a CSS property value in a CSS class is by using a CSS variable in the CSS class property value, and then use JavaScript and the DOM to change the CSS variable. The end result is that the styling on the device screen will immediately change when the code runs that sets the new CSS variable value. So, code changes the CSS variable, and the CSS variable is used in the CSS class setting. Note that a CSS class name and a JavaScript Class are two different things.
CSS - Styling
JavaScript and DOM
It is also possible to run a function in response to media queries (changes in the device viewport - like width of the device screen) using the
matchMedia()
method.您无法即时修改 CSS 类的成员。但是,您可以使用新的 css 类实现在页面上引入新的
标记,然后切换该类。示例:
您想要完全更改该类,因此创建一个新的样式元素:
然后通过 jQuery 进行简单的替换:
You can't modify the members of a CSS class on the fly. However, you could introduce a new
<style>
tag on the page with your new css class implementation, and then switch out the class. Example:You want to change that class entirely, so you create a new style element:
You then do a simple replacement via jQuery:
为什么不直接使用
.class
选择器来修改该类中每个对象的属性?即:
$('.myclass').css('color: red;');
Why not just use a
.class
selector to modify the properties of every object in that class?ie:
$('.myclass').css('color: red;');
YUI 2 和 3 有一个模块样式表,可以让您做到这一点(使用 javascript 动态编辑样式表)。 http://yuilibrary.com/yui/docs/stylesheet/。所以我认为这是可能的。这与 $(".some").css({...}) 不同,但实际上从样式表中更改/添加/删除样式定义,就像用户要求的那样。
YUI 2 and 3 has a module stylesheet that will let you do just that (edit stylesheets on the fly with javascript). http://yuilibrary.com/yui/docs/stylesheet/. So I think it is possible. This is not the same as $(".some").css({...}) but really change/add/remove styles definition from stylesheet, just like the user asked.
好吧..有同样的问题并解决了它,但解决方案可能并不适合所有人。
如果您知道要删除的样式表和规则的索引,请尝试类似
document.styleSheets[1].deleteRule(0);
。从一开始,我就有了我的 main.css (索引 0)文件。然后,我创建了一个新文件 js_edit.css (索引 1),该文件仅包含一个规则,其中包含我想要在页面完成加载时删除的属性(在一堆其他 JS 函数之后) )。
现在,由于 js_edit.css 在 main.css 之后加载,您可以根据需要在 js_edit.css 中插入/删除规则,它们将会覆盖 main.css 中的内容。
x.cssRules.length
返回第二个(索引 1)样式表中的规则数,从而在末尾插入新规则。我确信您可以使用一堆 for 循环来搜索要修改的规则/属性,然后在同一张表中重写整个规则,但我发现这种方式更适合我的需求。
http://www.quirksmode.org/dom/w3c_css.html 对我帮助很大。
Okay.. had the same problem and fixed it, but the solution may not be for everyone.
If you know the indexes of the style sheet and rule you want to delete, try something like
document.styleSheets[1].deleteRule(0);
.From the start, I had my main.css (index 0) file. Then, I created a new file, js_edit.css (index 1), that only contained one rule with the properties I wanted to remove when the page had finished loading (after a bunch of other JS functions too).
Now, since js_edit.css loads after main.css, you can just insert/delete rules in js_edit.css as you please and they will override the ones in main.css.
x.cssRules.length
returns the number of rules in the second (index 1) style sheet thus inserting the new rule at the end.I'm sure you can use a bunch of for-loops to search for the rule/property you want to modify and then rewrite the whole rule within the same sheet, but I found this way simpler for my needs.
http://www.quirksmode.org/dom/w3c_css.html helped me a lot.
这可能是迟到的讨论,但我需要像这里讨论的东西,但没有找到任何真正做我想做的事情,并且很容易做到。我需要的是隐藏和显示大量元素,而无需单独显式访问每个元素,以某种方式更新它们,从而将显示样式更改为隐藏或从隐藏更改为隐藏。所以我想出了以下方法:
通过切换嵌入和命名样式表中的 bclass 规则(该样式表位于任何其他相关样式表之后,在本例中带有 aclass 规则),我可以仅更新其中的显示 css 规则放置并让它覆盖 aclass 规则,该规则也有自己的显示规则。
这种技术的美妙之处在于它非常简单,有效地一行就可以完成实际工作,它不需要任何库,例如 JQuery 或插件,并且更新所有发生更改的地方的实际工作apply 由浏览器的 css 核心功能执行,而不是在 JavaScript 中执行。此外,它还适用于 IE 9 及更高版本、Chrome、Safari、Opera 以及 MicroSoft Edge 可以模拟的所有其他浏览器,适用于台式机和平板电脑/手机设备。
This may be late to the discussion, but I needed something like what is being talked about here, but didn't find anything that really did what I wanted, and did it easily. What I needed was to hide and show numerous elements without explicitly visiting each element individually to update them in some way that changed the display style to and from hidden. So I came up with the following:
By toggling the bclass rule in the embedded and named stylesheet, which comes after the any other relevant style sheets, in this case one with the aclass rule, I could update the just the display css rule in one place and have it override the aclass rule, which also had it's own display rule.
The beauty of this technique is that it is so simple, effectively one line that does the actual work, it doesn't require any libraries, such as JQuery or plug-ins, and the real work of updating all of the places where the change applies is performed by the browser's css core functionality, not in JavaScript. Also, it works in IE 9 and above, Chrome, Safari, Opera, and all of the other browsers that MicroSoft Edge could emulate, for desktop and tablet/phones devices.
你真的应该重新考虑你处理这个问题的方法。使用精心设计的选择器并附加类可能是这种方法的更优雅的解决方案。据我所知你不能修改外部CSS。
You should really rethink your approach to this issue. Using a well crafted selector and attaching the class may be a more elegant solution to this approach. As far as I know you cannot modify external CSS.
此解决方案修改 Cycne 以使用 ES6 语法并提前退出外部样式表的循环。此解决方案不修改外部样式表
例如,您的 HTML head 部分中还必须至少有一个样式标记
This solution modifies Cycne's to use ES6 syntax and exit the loop early for external stylesheets. This solution does not modify external stylesheets
You must also have at least one style tag in your HTML head section, for example