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

发布于 2024-11-30 20:46:23 字数 390 浏览 1 评论 0原文

我遇到了一个独特的情况,到目前为止我还无法找到解决方案:动态为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

蓬勃野心 2024-12-07 20:46:23

与这里的一些答案相反,使用 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.

‘画卷フ 2024-12-07 20:46:23

演示IE demo

您可以使用以下函数:

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

功能

  • 该函数是用 vanilla-js 编写的,因此它比 jQuery 有更好的性能替代方案
  • 第一次调用 setStyle 后会创建一个样式表,因此如果您不调用它,它将不会创建任何样式表。
  • 相同的样式表被重复用于以下 setStyle 调用。
  • 该函数返回对与您添加的 CSS 组关联的节点的引用。如果您使用该节点作为第二个参数再次调用该函数,它将用新的 CSS 替换旧的 CSS。

示例

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

浏览器支持

至少,它适用于 IE9、FF3、Chrome 1、Safari 4、Opera 10.5。

还有一个 IE 版本,它可以在现代浏览器和旧版本浏览器上运行IE!
(适用于 IE8 和 IE7,但可能会使 IE6 崩溃)。

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
  • One stylesheet is created after the first call to setStyle, so if you don't call it, it won't create any stylesheet.
  • The same stylesheet is reused for the following calls of 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.

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.

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

不疑不惑不回忆 2024-12-07 20:46:23

好问题。这里的很多答案都有一个与您所问的直接矛盾的解决方案

“我知道如何使用 jQuery 为元素分配宽度、高度等,但我想做的是实际上更改在样式表,以便动态创建的值可以分配给多个元素。

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

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

这样,你可以设置样式表 css 规则,而不是附加内联样式。

希望这有帮助!

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:

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.

Hope this helps!

原来是傀儡 2024-12-07 20:46:23

就像 @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);
}

这个解决方案将通过每次调整大小时仅修改一次 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:

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

夏至、离别 2024-12-07 20:46:23

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

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

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

$('<style>.someClass {color: red;} input::-webkit-outer-spin-button: {display: none;}</style>')
.appendTo('head'); 
美人如玉 2024-12-07 20:46:23

我有一个更改特定 CSS 类中的值的解决方案。但只有当你将 CSS 保留在标签中时它才有效。如果您只是保留外部文件(例如)到 CSS 的链接。

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

这个解决方案行不通。

例如,如果您的 css 如下所示:

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

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

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

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

}

然后只需将标签变量更改为样式标签 id 并执行:

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

这与 $('.foo').css('height','50px'); 之间的区别是,当您使用 jQuery 的 css 方法执行此操作时,所有具有 .foo 类的元素将在 DOM 中具有可见的 style='height:50px' 。如果你按照我的方式做,元素不会被改变,你唯一会看到的是 class='foo'

优点

  • 清除 DOM
  • 你可以修改你想要的属性,而不需要替换整个样式

缺点强>

  • 仅限内部CSS
  • 您必须找到要编辑的特定样式标签

希望它能有所帮助。

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.

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

this solution won't work.

If your css looks like this for example:

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

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.

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:

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'

Advantages

  • Clear DOM
  • You can modify the property you want without replacing the whole style

Disadvantages

  • Only internal CSS
  • You have to find specific style tag you want to edit

Hope it helps anyhow.

朱染 2024-12-07 20:46:23

动态修改 CSS 类中的 CSS 属性值的方法是在 CSS 类属性值中使用 CSS 变量,然后使用 JavaScript 和 DOM 来更改 CSS 变量。最终结果是,当设置新 CSS 变量值的代码运行时,设备屏幕上的样式将立即更改。因此,代码更改了 CSS 变量,并且 CSS 变量用于 CSS 类设置。请注意,CSS 类名和 JavaScript 类是两个不同的东西。

  • 使用 CSS 变量
  • 将 CSS 变量放置在静态 CSS 类属性值通常所在的位置
  • 使用代码设置新的 CSS 变量值
  • 对 CSS 变量的更改会更改 CSS 类属性值,并导致设备屏幕上的样式发生变化

CSS - 样式化

<style>
  :root { /* Set CSS variable values - These values can be changed with JavaScript 
    and DOM */
  --myCSS_ValueOne: initialValue;

  }

  .classNameHere {
    property_Name_Here: var(--myCSS_ValueOne);/* This CSS property gets its value from
    the CSS variable */

  }

</style>

JavaScript 和 DOM

<script>
  var r = document.querySelector(':root');//Get global root element

  function setA_NewCSS_VariableValue() {
    r.style.setProperty('--myCSS_ValueOne', 'the_New_Value');// Set a new CSS variable
      //value which immediately changes the CSS class setting because the CSS
      //property setting uses a CSS Variable -
  }
</script>

还可以使用 matchMedia() 方法运行一个函数来响应媒体查询(设备视口的变化 - 例如设备屏幕的宽度)。

var x = window.matchMedia("(max-width: 300px)")
x.addListener(setA_NewCSS_VariableValue) // create a listener function that runs
//when the viewport is less than, or equal to, 300 pixels wide.

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.

  • Use a CSS Variable
  • Put the CSS variable where the static CSS class property value would normally be
  • Use code to set a new CSS variable value
  • The change to the CSS variable changes the CSS class property value and that causes the styling on the device screen to change

CSS - Styling

<style>
  :root { /* Set CSS variable values - These values can be changed with JavaScript 
    and DOM */
  --myCSS_ValueOne: initialValue;

  }

  .classNameHere {
    property_Name_Here: var(--myCSS_ValueOne);/* This CSS property gets its value from
    the CSS variable */

  }

</style>

JavaScript and DOM

<script>
  var r = document.querySelector(':root');//Get global root element

  function setA_NewCSS_VariableValue() {
    r.style.setProperty('--myCSS_ValueOne', 'the_New_Value');// Set a new CSS variable
      //value which immediately changes the CSS class setting because the CSS
      //property setting uses a CSS Variable -
  }
</script>

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.

var x = window.matchMedia("(max-width: 300px)")
x.addListener(setA_NewCSS_VariableValue) // create a listener function that runs
//when the viewport is less than, or equal to, 300 pixels wide.
旧伤还要旧人安 2024-12-07 20:46:23

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

Sample.css

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

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

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

然后通过 jQuery 进行简单的替换:

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

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:

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:

$('.someClass').removeClass('someClass').addClass('someClassReplacement');
离不开的别离 2024-12-07 20:46:23
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'});
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'});
格子衫的從容 2024-12-07 20:46:23

为什么不直接使用 .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;');

第七度阳光i 2024-12-07 20:46:23

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.

花间憩 2024-12-07 20:46:23

好吧..有同样的问题并解决了它,但解决方案可能并不适合所有人。

如果您知道要删除的样式表和规则的索引,请尝试类似 document.styleSheets[1].deleteRule(0);

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

现在,由于 js_edit.cssma​​in.css 之后加载,您可以根据需要在 js_edit.css 中插入/删除规则,它们将会覆盖 ma​​in.css 中的内容。

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

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.

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.

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.

半窗疏影 2024-12-07 20:46:23

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

<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>  
<button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';">
  Show
</button>

通过切换嵌入和命名样式表中的 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:

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

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.

美人骨 2024-12-07 20:46:23

你真的应该重新考虑你处理这个问题的方法。使用精心设计的选择器并附加类可能是这种方法的更优雅的解决方案。据我所知你不能修改外部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.

半透明的墙 2024-12-07 20:46:23

此解决方案修改 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);

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

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

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

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

<style> .paintBox {background-color: white;}</style>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文