元素上的删除样式

我在想这是否可行。

有一种元素

<div id="sample_id" style="width:100px; height:100px; color:red;">

所以我想删除 宽度: 100px;身高: 100px;

结果就是

<div id="sample_id" style="color:red;">

任何帮助都将不胜感激。 :)

278875 次浏览

像这样使用

 $("#sample_id").css("width", "");
$("#sample_id").css("height", "");

使用 javascript

但这取决于你想做什么。如果你只想改变高度和宽度,我建议这样做:

{
document.getElementById('sample_id').style.height = '150px';
document.getElementById('sample_id').style.width = '150px';




}

要完全移除它,请移除样式,然后重新设置颜色:

getElementById('sample_id').removeAttribute("style");
document.getElementById('sample_id').style.color = 'red';

当然,剩下的唯一问题就是您希望这种情况发生在哪个事件上。

$("#sample_id").css({ 'width' : '', 'height' : '' });

更新: 有关更好的方法,请参考布莱克斯在 同样的线索中的回答。


如果您不反对使用 JavaScript 和 Regex,那么可以使用下面的解决方案来查找 style属性中的所有 widthheight属性以及 replace属性,而不需要任何东西。

//Get the value of style attribute based on element's Id
var originalStyle = document.getElementById('sample_id').getAttribute('style');


var regex = new RegExp(/(width:|height:).+?(;[\s]?|$)/g);
//Replace matches with null
var modStyle = originalStyle.replace(regex, "");


//Set the modified style value to element using it's Id
document.getElementById('sample_id').setAttribute('style', modStyle);

您可以使用纯 Javascript 编辑样式。不需要库,所有浏览器都支持,除了 IE,您需要将其设置为 ''而不是 null(参见注释)。

var element = document.getElementById('sample_id');


element.style.width = null;
element.style.height = null;

有关更多信息,请参考 MDN 上的 HTMLElement.style文档。

var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");

从技术上讲,指定 auto on width 和 height 元素与删除它们是一样的:

images[i].style.height = "auto";
images[i].style.width = "auto";

您可以简单地设置样式为[ 没有] ,它强制 CSS 假装样式从来没有分配给给定的元素。

var element = document.getElementById('sample_id');


element.style.width = "unset";
element.style.height = "unset";

你可以用这个方法,

var element = document.getElementById("sample_id");
element.style.removeProperty("width");
element.style.removeProperty("height");