javascript 通过javascript删除元素及其所有子元素的背景图像的功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4024837/
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-10-25 10:12:14  来源:igfitidea点击:

Function to remove background-images for an element and all its children via javascript

javascriptjquerycssjquery-ui

提问by Derek Adair

I would like to remove all CSS background images for a given element and allof its children with Javascript. This question is sort-of a spin off on another questionI asked. The end goal is the same, to skin jQuery UI widgets.

我想使用 Javascript删除给定元素及其所有子元素的所有 CSS 背景图像。这个问题有点像我问的另一个问题。最终目标是相同的,即为 jQuery UI 小部件设置外观。

I am currently using jquery/jquery-uiif any of would use these to solve the problem.

我目前正在使用jquery/ jquery-ui如果有任何人会使用这些来解决问题。

Any ideas?

有任何想法吗?

bonus:

奖金:

It would be wonderful to be able to remove background images for different jquery-ui states, BUT i've all but resolved myself to overriding these bg images via CSS.

能够删除不同 jquery-ui 状态的背景图像会很棒,但我几乎决定自己通过 CSS 覆盖这些 bg 图像。

EX:ui-state-hover, ui-state-active both have background images associated with them.

例如:ui-state-hover、ui-state-active 都有与之关联的背景图像。

or

或者

Please let me know if you think any kind of programmatic style overrides should not be done this way (please supply your reasoning).

如果您认为不应以这种方式进行任何类型的编程风格覆盖,请告诉我(请提供您的理由)。

回答by Harmen

You could just use an easy jQuery selector (might be slow though)

你可以只使用一个简单的 jQuery 选择器(虽然可能会很慢)

// You might now need the !important, but it overrules other !important's
$( '*', givenElement ).css( 'backgroundImage', '0 !important' );

But it's better to just add a certain class to your parent element, and then use normal CSS to style the children. For example:

但是最好只将某个类添加到您的父元素,然后使用普通的 CSS 来设置子元素的样式。例如:

// Javascript
$( givenElement ).addClass( 'stateX' );

// CSS, basic example to give you an idea
.stateX div, .stateX span {
    background-image: 0;
}

.stateY div, .stateY span {
    background-image: url( someimage.png );
}

回答by Thomas F.

function removeChildBackgrounds(parent) {
  parent.style.backgroundImage = "none";
  var childNodes = parent.childNodes;
  for(var i=0;i<childNodes.length;i++) {
    removeChildBackgrounds(childNodes[i]);
  }
}

This would remove all backgrounds recursively, starting with the parent node.

这将递归地删除所有背景,从父节点开始。