【发布时间】:2011-11-03 05:04:19
【问题描述】:
我发现的所有其他答案都只删除了属性的设置,而不是完全删除了属性。我正在将一个元素从绝对定位更改为固定定位。我需要删除 right 定位属性并将其替换为 margin-right ,以便该元素位于其父 DIV 内。如果未删除 right 属性,则元素会一直移动到屏幕的右侧,而不是像我需要的那样移动到 DIV 的右侧。任何人都可以就如何实现这一点提出建议吗?
【问题讨论】:
我发现的所有其他答案都只删除了属性的设置,而不是完全删除了属性。我正在将一个元素从绝对定位更改为固定定位。我需要删除 right 定位属性并将其替换为 margin-right ,以便该元素位于其父 DIV 内。如果未删除 right 属性,则元素会一直移动到屏幕的右侧,而不是像我需要的那样移动到 DIV 的右侧。任何人都可以就如何实现这一点提出建议吗?
【问题讨论】:
尝试将其设置为默认值auto
$(element).css('right', 'auto');
【讨论】:
All of the other answers I have discovered only remove the setting of the attribute, and not the attribute completely.
$('div').css({'right' : '', 'margin-right' : '100px'});
如果这不起作用,请尝试将其设置为默认值auto
【讨论】:
在我看来,最干净的方法是从元素的CSSStyleDeclaration 中完全删除该属性,而不是仅仅用某种空/零/默认值覆盖它:
$(".foo").prop("style").removeProperty("right");
$(".foo").prop("style").removeProperty("background-color");
【讨论】:
尝试将right 设置为0px,然后设置margin-right。
$('div').css({'right' : '0px', 'margin-right' : '100px'});
【讨论】:
你可以试试下面的代码
$.fn.removeCss=function(toDelete) {
var props = $(this).attr('style').split(';');
var tmp = -1;
for( var p=0; p<props.length; p++) {
if(props[p].indexOf(toDelete) !== -1 ) {
tmp=p
}
}
if(tmp !== -1) {
props.splice(tmp, 1);
}
return $(this).attr('style',props.join(';'));
}
example usage:
$(selector).removeCss('color');
【讨论】: