从样式中删除背景图像

时间:2011-11-07 03:50:03

标签: javascript jquery css background-image

如何从元素样式中删除背景图像。我不想将其设置为无或0.我想完全删除它。它与另一个类中定义的moz-linear-gradient冲突。

<div style="background-image:url(http://domain.com/1.jpg); width:100px" class="mozgradient"></div>

6 个答案:

答案 0 :(得分:13)

你试过了吗?

$(".mozgradient").css("background", "");

将背景设置为空字符串应删除内联样式,以使类和其他样式表设置生效,但不应影响内联设置的其他样式,如width。 (在这种情况下,使用mozgradient类从所有元素中删除它可以防止您所讨论的冲突。)

来自the jQuery .css() doco

  

将样式属性的值设置为空字符串 - 例如$('#mydiv')。css('color','') - 如果已经直接应用了元素,则从元素中删除该属性,无论是在HTML样式属性中,还是通过jQuery的.css()方法,还是直接应用DOM操作样式属性。

答案 1 :(得分:2)

我不完全确定你的目标是什么,但我假设你在div标签上有内联样式,并且通过CSS,你试图超越它。

这里唯一的选择是你的css文件中的!important标志。所以在你的css文件中你有这个:

.mozgradient {background-image(whatever) !important}

更新:

我现在看到你正试图通过jQuery来做。试试这个:

var divWidth = $yourDiv.css('width');

$yourDiv.removeAttr('style').css('width', divWidth);

虽然请注意,只有“宽度”才是您要保留的唯一css内联样式。如果那里可能有任何内联样式,你必须使用上面的CSS选项使用!important或使用jQuery,抓取整个样式属性并使用REGEX弄脏来专门解析任何背景图像样式。

更新II:

好的,根据评论,这很棘手。挑战在于可以通过style属性应用任意数量的内联样式(呃!我感觉到你的痛苦!)我们只想清除background-image以便我们可以让外部CSS处理它。

这是另一种选择:

// create a div and attach the class to it
$testDiv = $('<div>').class('mozgradient').css('display','none');

// stick it in the DOM
$('body').append($testDiv);

// now cache any background image information
var bgndImg = $testDiv.css('background-image');

// get rid of the test div you want now that we have the info we need
$testDiv.destroy();

// now that we have the background-image information 
// from the external CSS file, we can re-apply it
// to any other element on the page with that class
// name to over-ride the inline style
$('.mozgradient').css('background-image',bgndImg);

笨重,但我觉得它很有用。

答案 2 :(得分:2)

如果您想动态删除背景图片,请在jquery或inn CSS $("selector").css();中使用background:none功能。请参阅:http://jsfiddle.net/creativegala/um3Ez/

答案 3 :(得分:0)

解决方法是“重置”该属性。在这种情况下,我认为以下应该可以解决这个问题:

div[class="mozgradient"] { background-image: none !important; }

答案 4 :(得分:0)

$(div you use).removeAttr('style')

这应该删除样式

$(div you use).attr('style', 'width: 100px');

然后应该添加指定的样式只有高度

不确定它是否是你想要的

答案 5 :(得分:0)

处理此问题的最佳方法是在HTML级别或用于创建HTML的任何服务器端脚本中。只是让它不打印样式属性。一旦它存在,它在CSS级联中具有最高优先级,因此它会超越类或id定义中的任何其他内容。

第二个最佳选择是在使用JavaScript加载后覆盖它。您无法将其删除,但只要您可以为其添加id标记,就可以将其替换为尝试传递的任何类型。

.mozgradient { background-image:url(http://domain.com/2.jpg); } /* will not work */
#fixedelement { background-image:url(http://domain.com/2.jpg); } /* will not work */
<div style="background-image:url(http://domain.com/1.jpg); width:100px" class="mozgradient" id="fixedelement"></div>
<script type="text/javascript">
fixedelement.style.backgroundImage = 'url(http://domain.com/2.jpg)'; /* will work */
</script>