在 Javascript 中更改类的 CSS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5753680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:42:45  来源:igfitidea点击:

Change CSS of class in Javascript?

javascriptcss

提问by Skizit

I've got a class with the display set to noneI'd like to in Javascript now set it to inlineI'm aware I can do this with an idwith getElementByIdbut what's the cleanest way to do it with a class?

我有一个类,显示设置为noneId like to in Javascript 现在将其设置为inline我知道我可以用idwithgetElementById来做到这一点,但是用一个类来做到这一点最干净的方法是什么?

采纳答案by T.J. Crowder

You cando that — actually change style rules related to a class — using the styleSheetsarray (MDC link, MSDN link), but frankly you're probably better off (as changelog said) having a separate style that defines the display: noneand then removing that style from elements when you want them no longer hidden.

可以这样做 - 实际上更改与类相关的样式规则 - 使用styleSheets数组(MDC 链接MSDN 链接),但坦率地说,您可能最好(如更改日志所述)拥有一个单独的样式来定义display: none然后删除该样式当您希望它们不再隐藏时,来自元素。

回答by Znarkus

Do you mean something like this?

你的意思是这样的吗?

var elements = document.getElementsByClassName('hidden-class');
for (var i in elements) {
  if (elements.hasOwnProperty(i)) {
    elements[i].className = 'show-class';
  }
}

Then the CSS

然后是 CSS

.hidden-class { display: none; }
.show-class { display: inline; }

回答by Spoike

You can use getElementsByClassNamein which you'll get an array of elements. However this is not implemented in older browsers. In those cases getElementsByClassNameis undefinedso the code has to iterate through elements and check which ones have the desired class name.

您可以使用getElementsByClassName其中您将获得一个元素数组。然而,这在较旧的浏览器中没有实现。在这些情况下getElementsByClassNameundefined这样的代码,通过元素和检查哪些具有期望的类名称有迭代

For this you should use a javascript framework such as jQuery, mootools, prototype, etc.

为此,您应该使用 javascript 框架,例如 jQuery、mootools、prototype 等。

In jQuery it could be done with a one-liner as this:

在 jQuery 中,它可以使用单线完成,如下所示:

$('.theClassName').css('display', 'inline')

回答by Soyoes

you can create new style rule instead.

您可以改为创建新的样式规则。

var cssStyle = document.createElement('style');
cssStyle.type = 'text/css';
var rules = document.createTextNode(".YOU_CLASS_NAME{display:hidden}");
cssStyle.appendChild(rules);
document.getElementsByTagName("head")[0].appendChild(cssStyle);

$("#YOUR_DOM_ID").addClass("YOUR_CLASS_NAME");

回答by tomasb

You may like to exploit/rewrite this function:

你可能想利用/重写这个函数:

function getStyleRule(ruleClass, property, cssFile) {
    for (var s = 0; s < document.styleSheets.length; s++) {
        var sheet = document.styleSheets[s];
        if (sheet.href.endsWith(cssFile)) {
            var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
            if (rules == null) return null;
            for (var i = 0; i < rules.length; i++) {
                if (rules[i].selectorText == ruleClass) {
                    return rules[i].style[property];
                    //or rules[i].style["border"]="2px solid red";
                    //or rules[i].style["boxShadow"]="4px 4px 4px -2px rgba(0,0,0,0.5)";
                }
            }
        }
    }
    return null;
}
  • to scan all style sheets attached pass "" as third argument, otherwise something like "index.css"
  • ruleClass contains starting '.'
  • if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) condition improvement found here https://stackoverflow.com/a/16966533/881375
  • don't forget to use javascript syntax over css properties, e.g. box-shadow vs. boxShadow
  • 扫描所有附加的样式表,将“”作为第三个参数,否则类似于“index.css”
  • ruleClass 包含开头的 '.'
  • if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) 条件改进在这里找到https://stackoverflow.com/a/16966533/881375
  • 不要忘记在 css 属性上使用 javascript 语法,例如 box-shadow 与 boxShadow

回答by Remigius Stalder

Although this is long gone, here a few remarks:

虽然这已经过去很久了,但这里有几点说明:

  • Using display: inlineto make things visible again may spoil the page flow. Some elements are displayed inline, others block etc. This should be preserved. Hence, only define a .hidden style and remove it to make things visible again.

  • How to hide: There are (at least) two ways to hide elements, one is the above mentioned display: nonewhich basically makes the element behave as if it was not there, and the visibility: hiddenwhich renders the element invisible but keeps the space it occupies. Depending on what you want to hide, the visibility may be a better choice, as other elements will not move when showing/hiding an element.

  • Adding/removing classes vs. manipulating CSS rules: The result is quite different. If you manipulate the CSS rules, all elements having a certain CSS class are affected - now and in the future, i.e. new elements dynamically added to the DOM are also hidden, whereas when you add/remove a class, you must make sure that newly added elements also have the class added/removed. So, I'd say adding/removing classes works well for static HTML, whereas manipulating CSS rules might be a better choice for dynamically created DOM elements.

  • 使用display: inline使事物再次可见可能会破坏页面流。一些元素是内联显示的,其他元素是块显示的等等。这应该被保留。因此,只需定义一个 .hidden 样式并将其删除以使其再次可见。

  • 如何隐藏:有(至少)两种隐藏元素的方法,一种是上面提到的display: none,它基本上使元素表现得好像它不存在一样,visibility: hidden它使元素不可见但保持它占据的空间。根据您要隐藏的内容,可见性可能是更好的选择,因为其他元素在显示/隐藏元素时不会移动。

  • 添加/删除类与操作 CSS 规则:结果完全不同。如果您操作 CSS 规则,则所有具有特定 CSS 类的元素都会受到影响 - 现在和将来,即动态添加到 DOM 的新元素也会被隐藏,而当您添加/删除一个类时,您必须确保新的添加的元素也添加/删除了类。因此,我认为添加/删除类对于静态 HTML 效果很好,而操作 CSS 规则对于动态创建的 DOM 元素可能是更好的选择。

回答by Kamil Kie?czewski

To change CLASS you need to edit document stylesheets

要更改 CLASS,您需要编辑文档样式表

[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
    .style.display='inline';

[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
    .style.display='inline';
.box {
  margin: 10px;
  padding: 10px;
  background: yellow;
  display: none
}
<div class="box" >My box 1</div>
<div class="box" >My box 2</div>
<div class="box" >My box 3</div>

回答by changelog

Best way to do it is to have a hidden class, like so:

最好的方法是有一个隐藏的类,像这样:

.hidden { display: none; }

After that, there is a classNameattribute to every element in JavaScript. You can just manipulate that string to remove occurrences of the hiddenclass and add another one.

之后,classNameJavaScript 中的每个元素都有一个属性。您可以操作该字符串以删除hidden该类的出现并添加另一个。

One piece of advice: Use jQuery. Makes it easier to deal with that kind of stuff, you can do it like:

一条建议:使用jQuery。使处理这类事情变得更容易,您可以这样做:

$('#element_id').removeClass('hidden').addClass('something');