简体   繁体   English

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

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

I would like to remove all CSS background images for a given element and all of its children with Javascript. 我想删除给定元素的所有CSS背景图像及其所有带有Javascript的子元素。 This question is sort-of a spin off on another question I asked. 这个问题有点像我提出的另一个问题 The end goal is the same, to skin jQuery UI widgets. 最终目标与jQuery UI小部件的外观相同。

I am currently using jquery / jquery-ui if 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). 如果您认为不应以这种方式进行任何编程风格的替代(请提供您的理由),请告诉我。

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. 但是最好只是将某个类添加到您的父元素,然后使用常规CSS为子元素设置样式。 For example: 例如:

// 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 );
}
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. 从父节点开始,这将递归删除所有背景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM