使用JavaScript / jQuery动态修改CSS类属性值

时间:2022-09-20 13:15:08

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.

我遇到了一个独特的情况,到目前为止我无法找到解决方案:动态地为CSS样式赋值。我知道如何使用jQuery为元素分配宽度,高度等,但我想要做的是实际更改样式表中定义的值,以便可以将动态创建的值分配给多个元素。

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.

可以动态修改类中属性的值吗?我确定答案就在那里,我可能只是在我的搜索中没有使用正确的术语。希望我能很好地描述这个问题。 TIA。

14 个解决方案

#1


26  

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.

与此处的一些答案相反,使用Javascript编辑样式表本身不仅可行,而且性能更高。只需执行$('。myclass')。css('color:red')将最终循环遍历与选择器匹配的每个项目并单独设置样式属性。这是非常低效的,如果你有数百个元素,它会导致问题。

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.

更改项目上的类是一个更好的主意,但您仍然遇到同样的问题,因为您正在更改N个项目的属性,这可能是一个很大的数字。一个更好的解决方案可能是在一个单个父项或少数父项上更改类,然后使用css中的“Cascade”命中目标项。这适用于大多数情况,但不是全部。

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.

有时您需要将很多项目的CSS更改为动态的内容,或者通过点击少数父母来实现这一点是没有好办法的。更改样式表本身,或添加一个小的新样式来覆盖现有的css是一种非常有效的方式来更改项目的显示。您只在一个位置与DOM交互,浏览器可以非常有效地处理这些更改。

jss is one library that helps make it easier to directly edit the stylesheet from javascript.

jss是一个库,可以帮助您更轻松地从javascript直接编辑样式表。

#2


21  

Demo, IE demo

You could use the following function:

您可以使用以下功能:

function setStyle(cssText) {
    var sheet = document.createElement('style');
    sheet.type = 'text/css';
    /* Optional */ window.customSheet = sheet;
    (document.head || document.getElementsByTagName('head')[0]).appendChild(sheet);
    return (setStyle = function(cssText, node) {
        if(!node || node.parentNode !== sheet)
            return sheet.appendChild(document.createTextNode(cssText));
        node.nodeValue = cssText;
        return node;
    })(cssText);
};

Features:

特征:

  • The function is written in vanilla-js, so it has better performance than jQuery alternatives
  • 该函数是用vanilla-js编写的,因此它比jQuery替代品具有更好的性能
  • One stylesheet is created after the first call to setStyle, so if you don't call it, it won't create any stylesheet.
  • 在第一次调用setStyle之后创建一个样式表,因此如果不调用它,它将不会创建任何样式表。
  • The same stylesheet is reused for the following calls of setStyle
  • 相同的样式表将重用于以下setStyle调用
  • The function return a reference to the node associated with the bunch of CSS that you have added. If you call the function again with that node as a second argument, it will replace the old CSS with the new one.
  • 该函数返回对与您添加的一堆CSS相关联的节点的引用。如果再次使用该节点作为第二个参数调用该函数,它将用新的CSS替换旧的CSS。

Example

var myCSS = setStyle('*{ color:red; }');
setStyle('*{ color:blue; }', myCSS); // Replaces the previous CSS with this one

Browser support

浏览器支持

At least, it works on IE9, FF3, Chrome 1, Safari 4, Opera 10.5.

至少,它适用于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).

还有一个IE版本,适用于现代浏览器和旧版本的IE! (适用于IE8和IE7,但可能会崩溃IE6)。

#3


18  

Nice question. A lot of the answers here had a solution directly contradicting what you were asking

好问题。这里的很多答案都有一个解决方案,直接与你提出的问题相矛盾

"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.
"

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:

jQuery .css样式元素内联:它不会改变物理CSS规则!如果你想这样做,我建议使用一个vanilla JavaScript解决方案:

document.styleSheets[0].cssRules[0].cssText = "\
     #myID {
         myRule: myValue;
         myOtherRule: myOtherValue;
     }";

This way, you're setting the stylesheet css rule, not appending an inline style.

这样,您将设置样式表css规则,而不是附加内联样式。

Hope this helps!

希望这可以帮助!

#4


8  

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:

就像@benvie所说的那样,更有效地更改样式表而不是使用jQuery.css(它将循环遍历集合中的所有元素)。每次调用函数时都不要在头部添加新样式也很重要,因为它会产生内存泄漏和数千个必须由浏览器单独应用的CSS规则。我会做这样的事情:

//Add the stylesheet once and store a cached jQuery object
var $style = $("<style type='text/css'>").appendTo('head'); 

function onResize() {
    var css = "\
        .someClass {\
            left:   "+leftVal+";\
            width:  "+widthVal+";\
            height: "+heightVal+";\
        }";

    $style.html(css);
}

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.

此解决方案将通过每次调整大小仅修改DOM一次来更改样式。请注意,对于有效的js缩小和压缩,您可能不希望漂亮地打印css,但我这样做是为了清晰。

#5


4  

Use jquery to add a style override in the <head>:

使用jquery在中添加样式覆盖:

$('<style>.someClass {color: red;} input::-webkit-outer-spin-button: {display: none;}</style>')
.appendTo('head'); 

#6


4  

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.

我有一个改变特定CSS类中的值的解决方案。但它只适用于将CSS保留在标记中。如果您只是从外部文件保留到CSS的链接。

<style src='script.js'></style>

this solution won't work.

这个解决方案不起作用。

If your css looks like this for example:

如果你的css看起来像这样:

<style id='style'>
.foo {
height:50px;
}
</style>

You can change a value of the tag using JS/jQuery.

您可以使用JS / jQuery更改标记的值。

I've written a function, perhaps it's not the best one but it works. You can improve it if you want.

我写了一个函数,也许它不是最好的函数,但它有效。如果你愿意,你可以改进它。

function replaceClassProp(cl,prop,val){

if(!cl || !prop || !val){console.error('Wrong function arguments');return false;}


// Select style tag value

var tag = '#style';

    var style = $(tag).text();
    var str = style;

// Find the class you want to change
    var n = str.indexOf('.'+cl);
    str = str.substr(n,str.length);
    n = str.indexOf('}');
    str = str.substr(0,n+1);

    var before = str;

// Find specific property

    n = str.indexOf(prop);
    str = str.substr(n,str.length);
    n = str.indexOf(';');
    str = str.substr(0,n+1);

// Replace the property with values you selected

    var after = before.replace(str,prop+':'+val+';');
    style=style.replace(before,after);

// Submit changes

    $(tag).text(style);

}

Then just change the tag variable into your style tag id and exegute:

然后只需将标记变量更改为样式标记id和exegute:

replaceClassProp('foo','height','50px');

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'

这与$('。foo')。css('height','50px')之间的区别;当你使用jQuery的css方法执行它时,所有具有.foo类的元素都将在DOM中具有可见的style ='height:50px'。如果你这样做,元素是不受影响的,你唯一能看到的就是class ='foo'

Advantages

优点

  • Clear DOM
  • 清除DOM
  • You can modify the property you want without replacing the whole style
  • 您可以修改所需的属性而无需替换整个样式

Disadvantages

缺点

  • Only internal CSS
  • 只有内部CSS
  • You have to find specific style tag you want to edit
  • 您必须找到要编辑的特定样式标记

Hope it helps anyhow.

无论如何希望它有所帮助。

#7


3  

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:

您无法动态修改CSS类的成员。但是,您可以在页面上使用新的css类实现引入新的

Sample.css

.someClass { border: 1px solid black; font-size: 20px; }

You want to change that class entirely, so you create a new style element:

您想要完全更改该类,因此您需要创建一个新的样式元素:

<style>
   .someClassReplacement { border: 1px solid white; font-size: 14px; }       
</style>

You then do a simple replacement via jQuery:

然后你通过jQuery做一个简单的替换:

$('.someClass').removeClass('someClass').addClass('someClassReplacement');

#8


2  

Why not just use a .class selector to modify the properties of every object in that class?

为什么不使用.class选择器来修改该类中每个对象的属性?

ie:

即:

$('.myclass').css('color: red;');

$('。myclass')。css('color:red;');

#9


1  

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.

YUI 2和3有一个模块样式表,可以让你做到这一点(使用javascript动态编辑样式表)。 http://yuilibrary.com/yui/docs/stylesheet/。所以我认为这是可能的。这与$(“。some”)。css({...})不同,但真的从样式表中更改/添加/删除样式定义,就像用户要求的那样。

#10


1  

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); .

如果您知道要删除的样式表和规则的索引,请尝试类似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).

从一开始,我就有了main.css(索引0)文件。然后,我创建了一个新文件js_edit.css(索引1),该文件只包含一个规则,其中包含我想在页面加载完成后删除的属性(在一堆其他JS函数之后)。

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.

现在,由于js_edit.css在main.css之后加载,你可以根据需要在js_edit.css中插入/删除规则,它们将覆盖main.css中的规则。

var x = document.styleSheets[1];
x.insertRule("p { font-size: 2rem; }", x.cssRules.length);

x.cssRules.length returns the number of rules in the second (index 1) style sheet thus inserting the new rule at the end.

x.cssRules.length返回第二个(索引1)样式表中的规则数,从而在末尾插入新规则。

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.

我确定你可以使用一堆for循环来搜索你想要修改的规则/属性,然后在同一张表中重写整个规则,但我发现这种方式对我的需求更简单。

http://www.quirksmode.org/dom/w3c_css.html helped me a lot.

http://www.quirksmode.org/dom/w3c_css.html对我帮助很大。

#11


1  

function changeStyle(findSelector, newRules) {
    // Change original css style declaration.   
    for ( s in document.styleSheets ) {
        var CssRulesStyle = document.styleSheets[s].cssRules;
        for ( x in CssRulesStyle ) {
            if ( CssRulesStyle[x].selectorText == findSelector) {
                for ( cssprop in newRules ) {
                    CssRulesStyle[x].style[cssprop] = newRules[cssprop];
                }

                return true;
            }
        }
    }

    return false;
}

changeStyle('#exact .myStyle .declaration', {'width':'200px', 'height':'400px', 'color':'#F00'});

#12


1  

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.

你应该重新考虑你对这个问题的处理方法。使用精心设计的选择器并附加类可能是这种方法的更优雅的解决方案。据我所知,你无法修改外部CSS。

#13


0  

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:

这可能是讨论的后期,但我需要的东西就像这里所讨论的内容,但没有找到任何真正做到我想要的东西,并且很容易做到。我需要的是隐藏和显示众多元素,而无需单独访问每个元素,以某种方式更新它们,从而改变隐藏的显示样式。所以我想出了以下内容:

<style>
  /* The bulk of the css rules should go here or in an external css file */
  /* None of these rules will be changed, but may be overridden */
  .aclass { display: inline-block; width: 50px; height: 30px; }
</style>
<style id="style">
  /* Only the rules to be changed should go in this style */
  .bclass { display: inline-block; }
</style>
<script>
  //
  // This is a helper function that returns the named style as an object.
  // This could also be done in other ways.
  // 
  function setStyle() { return document.getElementById( 'style' ); }
</script>
<div id="d1" class="aclass" style="background-color: green;">
  Hi
</div>
<!-- The element to be shown and hidden --> 
<div id="d2" class="aclass bclass" style="background-color: yellow;">
  there
</div>
<div id="d3" class="aclass" style="background-color: lightblue;">
  sailor
</div>
<hr />
<!-- These buttons demonstrate hiding and showing the d3 dive element -->
<button onclick="setStyle().innerHTML = '.bclass { display: none; }';">
  Hide
</button>&nbsp;&nbsp;
<button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';">
  Show
</button>

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.

通过在嵌入式和命名样式表中切换bclass规则,该样式表位于任何其他相关样式表之后,在这种情况下是一个带有aclass规则的样式表,我可以在一个地方更新显示css规则并让它覆盖aclass规则,它也有自己的显示规则。

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.

这种技术的优点在于它非常简单,有效地完成了实际工作,它不需要任何库,例如JQuery或插件,以及更新所有更改位置的实际工作apply由浏览器的css核心功能执行,而不是在JavaScript中执行。此外,它适用于IE 9及更高版本,Chrome,Safari,Opera以及MicroSoft Edge可以模拟的所有其他浏览器,适用于台式机和平板电脑/手机设备。

#14


0  

This solution modifies Cycne's to use ES6 syntax and exit the loop early for external stylesheets. This solution does not modify external stylesheets

此解决方案修改Cycne以使用ES6语法并提前退出循环以获取外部样式表。此解决方案不会修改外部样式表

function changeStyle(findSelector, newDeclarations) {
    // Change original css style declaration.
    document.styleSheets.forEach((sheet) => {
      if (sheet.href) return;
      const cssRulesList = sheet.cssRules;
      cssRulesList.forEach((styleRule) => {
        if (styleRule.selectorText === findSelector) {
          Object.keys(newDeclarations).forEach((cssProp) => {
            styleRule.style[cssProp] = newDeclarations[cssProp];
          });
        }
      });
    });
  }

  const styleDeclarations = {
    'width': '200px',
    'height': '400px',
    'color': '#F00'
  };
  changeStyle('.paintBox', styleDeclarations);

You must also have at least one style tag in your HTML head section, for example

例如,您的HTML头部分中还必须至少有一个样式标记

<style> .paintBox {background-color: white;}</style>

#1


26  

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.

与此处的一些答案相反,使用Javascript编辑样式表本身不仅可行,而且性能更高。只需执行$('。myclass')。css('color:red')将最终循环遍历与选择器匹配的每个项目并单独设置样式属性。这是非常低效的,如果你有数百个元素,它会导致问题。

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.

更改项目上的类是一个更好的主意,但您仍然遇到同样的问题,因为您正在更改N个项目的属性,这可能是一个很大的数字。一个更好的解决方案可能是在一个单个父项或少数父项上更改类,然后使用css中的“Cascade”命中目标项。这适用于大多数情况,但不是全部。

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.

有时您需要将很多项目的CSS更改为动态的内容,或者通过点击少数父母来实现这一点是没有好办法的。更改样式表本身,或添加一个小的新样式来覆盖现有的css是一种非常有效的方式来更改项目的显示。您只在一个位置与DOM交互,浏览器可以非常有效地处理这些更改。

jss is one library that helps make it easier to directly edit the stylesheet from javascript.

jss是一个库,可以帮助您更轻松地从javascript直接编辑样式表。

#2


21  

Demo, IE demo

You could use the following function:

您可以使用以下功能:

function setStyle(cssText) {
    var sheet = document.createElement('style');
    sheet.type = 'text/css';
    /* Optional */ window.customSheet = sheet;
    (document.head || document.getElementsByTagName('head')[0]).appendChild(sheet);
    return (setStyle = function(cssText, node) {
        if(!node || node.parentNode !== sheet)
            return sheet.appendChild(document.createTextNode(cssText));
        node.nodeValue = cssText;
        return node;
    })(cssText);
};

Features:

特征:

  • The function is written in vanilla-js, so it has better performance than jQuery alternatives
  • 该函数是用vanilla-js编写的,因此它比jQuery替代品具有更好的性能
  • One stylesheet is created after the first call to setStyle, so if you don't call it, it won't create any stylesheet.
  • 在第一次调用setStyle之后创建一个样式表,因此如果不调用它,它将不会创建任何样式表。
  • The same stylesheet is reused for the following calls of setStyle
  • 相同的样式表将重用于以下setStyle调用
  • The function return a reference to the node associated with the bunch of CSS that you have added. If you call the function again with that node as a second argument, it will replace the old CSS with the new one.
  • 该函数返回对与您添加的一堆CSS相关联的节点的引用。如果再次使用该节点作为第二个参数调用该函数,它将用新的CSS替换旧的CSS。

Example

var myCSS = setStyle('*{ color:red; }');
setStyle('*{ color:blue; }', myCSS); // Replaces the previous CSS with this one

Browser support

浏览器支持

At least, it works on IE9, FF3, Chrome 1, Safari 4, Opera 10.5.

至少,它适用于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).

还有一个IE版本,适用于现代浏览器和旧版本的IE! (适用于IE8和IE7,但可能会崩溃IE6)。

#3


18  

Nice question. A lot of the answers here had a solution directly contradicting what you were asking

好问题。这里的很多答案都有一个解决方案,直接与你提出的问题相矛盾

"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.
"

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:

jQuery .css样式元素内联:它不会改变物理CSS规则!如果你想这样做,我建议使用一个vanilla JavaScript解决方案:

document.styleSheets[0].cssRules[0].cssText = "\
     #myID {
         myRule: myValue;
         myOtherRule: myOtherValue;
     }";

This way, you're setting the stylesheet css rule, not appending an inline style.

这样,您将设置样式表css规则,而不是附加内联样式。

Hope this helps!

希望这可以帮助!

#4


8  

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:

就像@benvie所说的那样,更有效地更改样式表而不是使用jQuery.css(它将循环遍历集合中的所有元素)。每次调用函数时都不要在头部添加新样式也很重要,因为它会产生内存泄漏和数千个必须由浏览器单独应用的CSS规则。我会做这样的事情:

//Add the stylesheet once and store a cached jQuery object
var $style = $("<style type='text/css'>").appendTo('head'); 

function onResize() {
    var css = "\
        .someClass {\
            left:   "+leftVal+";\
            width:  "+widthVal+";\
            height: "+heightVal+";\
        }";

    $style.html(css);
}

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.

此解决方案将通过每次调整大小仅修改DOM一次来更改样式。请注意,对于有效的js缩小和压缩,您可能不希望漂亮地打印css,但我这样做是为了清晰。

#5


4  

Use jquery to add a style override in the <head>:

使用jquery在中添加样式覆盖:

$('<style>.someClass {color: red;} input::-webkit-outer-spin-button: {display: none;}</style>')
.appendTo('head'); 

#6


4  

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.

我有一个改变特定CSS类中的值的解决方案。但它只适用于将CSS保留在标记中。如果您只是从外部文件保留到CSS的链接。

<style src='script.js'></style>

this solution won't work.

这个解决方案不起作用。

If your css looks like this for example:

如果你的css看起来像这样:

<style id='style'>
.foo {
height:50px;
}
</style>

You can change a value of the tag using JS/jQuery.

您可以使用JS / jQuery更改标记的值。

I've written a function, perhaps it's not the best one but it works. You can improve it if you want.

我写了一个函数,也许它不是最好的函数,但它有效。如果你愿意,你可以改进它。

function replaceClassProp(cl,prop,val){

if(!cl || !prop || !val){console.error('Wrong function arguments');return false;}


// Select style tag value

var tag = '#style';

    var style = $(tag).text();
    var str = style;

// Find the class you want to change
    var n = str.indexOf('.'+cl);
    str = str.substr(n,str.length);
    n = str.indexOf('}');
    str = str.substr(0,n+1);

    var before = str;

// Find specific property

    n = str.indexOf(prop);
    str = str.substr(n,str.length);
    n = str.indexOf(';');
    str = str.substr(0,n+1);

// Replace the property with values you selected

    var after = before.replace(str,prop+':'+val+';');
    style=style.replace(before,after);

// Submit changes

    $(tag).text(style);

}

Then just change the tag variable into your style tag id and exegute:

然后只需将标记变量更改为样式标记id和exegute:

replaceClassProp('foo','height','50px');

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'

这与$('。foo')。css('height','50px')之间的区别;当你使用jQuery的css方法执行它时,所有具有.foo类的元素都将在DOM中具有可见的style ='height:50px'。如果你这样做,元素是不受影响的,你唯一能看到的就是class ='foo'

Advantages

优点

  • Clear DOM
  • 清除DOM
  • You can modify the property you want without replacing the whole style
  • 您可以修改所需的属性而无需替换整个样式

Disadvantages

缺点

  • Only internal CSS
  • 只有内部CSS
  • You have to find specific style tag you want to edit
  • 您必须找到要编辑的特定样式标记

Hope it helps anyhow.

无论如何希望它有所帮助。

#7


3  

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:

您无法动态修改CSS类的成员。但是,您可以在页面上使用新的css类实现引入新的

Sample.css

.someClass { border: 1px solid black; font-size: 20px; }

You want to change that class entirely, so you create a new style element:

您想要完全更改该类,因此您需要创建一个新的样式元素:

<style>
   .someClassReplacement { border: 1px solid white; font-size: 14px; }       
</style>

You then do a simple replacement via jQuery:

然后你通过jQuery做一个简单的替换:

$('.someClass').removeClass('someClass').addClass('someClassReplacement');

#8


2  

Why not just use a .class selector to modify the properties of every object in that class?

为什么不使用.class选择器来修改该类中每个对象的属性?

ie:

即:

$('.myclass').css('color: red;');

$('。myclass')。css('color:red;');

#9


1  

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.

YUI 2和3有一个模块样式表,可以让你做到这一点(使用javascript动态编辑样式表)。 http://yuilibrary.com/yui/docs/stylesheet/。所以我认为这是可能的。这与$(“。some”)。css({...})不同,但真的从样式表中更改/添加/删除样式定义,就像用户要求的那样。

#10


1  

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); .

如果您知道要删除的样式表和规则的索引,请尝试类似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).

从一开始,我就有了main.css(索引0)文件。然后,我创建了一个新文件js_edit.css(索引1),该文件只包含一个规则,其中包含我想在页面加载完成后删除的属性(在一堆其他JS函数之后)。

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.

现在,由于js_edit.css在main.css之后加载,你可以根据需要在js_edit.css中插入/删除规则,它们将覆盖main.css中的规则。

var x = document.styleSheets[1];
x.insertRule("p { font-size: 2rem; }", x.cssRules.length);

x.cssRules.length returns the number of rules in the second (index 1) style sheet thus inserting the new rule at the end.

x.cssRules.length返回第二个(索引1)样式表中的规则数,从而在末尾插入新规则。

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.

我确定你可以使用一堆for循环来搜索你想要修改的规则/属性,然后在同一张表中重写整个规则,但我发现这种方式对我的需求更简单。

http://www.quirksmode.org/dom/w3c_css.html helped me a lot.

http://www.quirksmode.org/dom/w3c_css.html对我帮助很大。

#11


1  

function changeStyle(findSelector, newRules) {
    // Change original css style declaration.   
    for ( s in document.styleSheets ) {
        var CssRulesStyle = document.styleSheets[s].cssRules;
        for ( x in CssRulesStyle ) {
            if ( CssRulesStyle[x].selectorText == findSelector) {
                for ( cssprop in newRules ) {
                    CssRulesStyle[x].style[cssprop] = newRules[cssprop];
                }

                return true;
            }
        }
    }

    return false;
}

changeStyle('#exact .myStyle .declaration', {'width':'200px', 'height':'400px', 'color':'#F00'});

#12


1  

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.

你应该重新考虑你对这个问题的处理方法。使用精心设计的选择器并附加类可能是这种方法的更优雅的解决方案。据我所知,你无法修改外部CSS。

#13


0  

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:

这可能是讨论的后期,但我需要的东西就像这里所讨论的内容,但没有找到任何真正做到我想要的东西,并且很容易做到。我需要的是隐藏和显示众多元素,而无需单独访问每个元素,以某种方式更新它们,从而改变隐藏的显示样式。所以我想出了以下内容:

<style>
  /* The bulk of the css rules should go here or in an external css file */
  /* None of these rules will be changed, but may be overridden */
  .aclass { display: inline-block; width: 50px; height: 30px; }
</style>
<style id="style">
  /* Only the rules to be changed should go in this style */
  .bclass { display: inline-block; }
</style>
<script>
  //
  // This is a helper function that returns the named style as an object.
  // This could also be done in other ways.
  // 
  function setStyle() { return document.getElementById( 'style' ); }
</script>
<div id="d1" class="aclass" style="background-color: green;">
  Hi
</div>
<!-- The element to be shown and hidden --> 
<div id="d2" class="aclass bclass" style="background-color: yellow;">
  there
</div>
<div id="d3" class="aclass" style="background-color: lightblue;">
  sailor
</div>
<hr />
<!-- These buttons demonstrate hiding and showing the d3 dive element -->
<button onclick="setStyle().innerHTML = '.bclass { display: none; }';">
  Hide
</button>&nbsp;&nbsp;
<button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';">
  Show
</button>

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.

通过在嵌入式和命名样式表中切换bclass规则,该样式表位于任何其他相关样式表之后,在这种情况下是一个带有aclass规则的样式表,我可以在一个地方更新显示css规则并让它覆盖aclass规则,它也有自己的显示规则。

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.

这种技术的优点在于它非常简单,有效地完成了实际工作,它不需要任何库,例如JQuery或插件,以及更新所有更改位置的实际工作apply由浏览器的css核心功能执行,而不是在JavaScript中执行。此外,它适用于IE 9及更高版本,Chrome,Safari,Opera以及MicroSoft Edge可以模拟的所有其他浏览器,适用于台式机和平板电脑/手机设备。

#14


0  

This solution modifies Cycne's to use ES6 syntax and exit the loop early for external stylesheets. This solution does not modify external stylesheets

此解决方案修改Cycne以使用ES6语法并提前退出循环以获取外部样式表。此解决方案不会修改外部样式表

function changeStyle(findSelector, newDeclarations) {
    // Change original css style declaration.
    document.styleSheets.forEach((sheet) => {
      if (sheet.href) return;
      const cssRulesList = sheet.cssRules;
      cssRulesList.forEach((styleRule) => {
        if (styleRule.selectorText === findSelector) {
          Object.keys(newDeclarations).forEach((cssProp) => {
            styleRule.style[cssProp] = newDeclarations[cssProp];
          });
        }
      });
    });
  }

  const styleDeclarations = {
    'width': '200px',
    'height': '400px',
    'color': '#F00'
  };
  changeStyle('.paintBox', styleDeclarations);

You must also have at least one style tag in your HTML head section, for example

例如,您的HTML头部分中还必须至少有一个样式标记

<style> .paintBox {background-color: white;}</style>