我在想这是否可能。
有这个元素。
<div id="sample_id" style="width:100px; height:100px; color:red;">
所以我想要移除 width:100px; 和 height:100px;
结果将是
<div id="sample_id" style="color:red;">
任何帮助都将不胜感激。 :)
我在想这是否可能。
有这个元素。
<div id="sample_id" style="width:100px; height:100px; color:red;">
所以我想要移除 width:100px; 和 height:100px;
结果将是
<div id="sample_id" style="color:red;">
你可以使用纯Javascript编辑样式。无需库,支持除IE外的所有浏览器,在IE中需要将null
设置为''
(请参见注释)。
var element = document.getElementById('sample_id');
element.style.width = null;
element.style.height = null;
了解更多信息,请参考 MDN 上的 HTMLElement.style 文档。
null
会悄无声息地失败,请改用''
代替。 - Oliver Joseph Ashmax-width
),您可以使用以下语法:element.style.maxWidth = '';
或者这种语法:element.style['max-width'] = '';
(翻译完成,已按要求返回结果) - zinginull
。请使用如@madhu所述的.removeProperty
方法。 - Haraldvar element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
.removeProperty("font-family")
而不是 .removeProperty("fontFamily")
。 - Toastrackenigma使用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';
更新:更好的方法请参考同一篇文章中Blackus的回答。
如果您不反对使用JavaScript和Regex,可以使用以下解决方案来查找style
属性中所有的width
和height
属性,并将它们替换为空
。
//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);
let assignStyles = props => { const { color, width, height } = props; elem.style = { color, width, height }; }
,编译一次并更有效,虽然(更)冗长,但对于动态需求也不实用。 - Nolovar element = document.getElementById('sample_id');
element.style.width = "unset";
element.style.height = "unset";
$("#sample_id").css({ 'width' : '', 'height' : '' });
在宽度和高度元素上指定auto与从技术上删除它们相同。使用原生JavaScript:
images[i].style.height = "auto";
images[i].style.width = "auto";
就像这样使用
$("#sample_id").css("width", "");
$("#sample_id").css("height", "");