96

これが可能かどうか疑問に思っていました。

こんな要素がある

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

だから私はwidth:100px;を削除したいです。高さ:100px;

結果は

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

どんな助けでも感謝します。:)

4

7 に答える 7

167

純粋な Javascript でスタイルを編集できます。''ライブラリは必要ありません。代わりにに設定する必要がある IE を除くすべてのブラウザーでサポートされていますnull(コメントを参照)。

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

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

詳細については、MDN のHTMLElement.styleドキュメントを参照してください。

于 2015-10-09T13:18:04.497 に答える
7

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';

もちろん、残っている唯一の問題は、これをどのイベントで発生させたいかということです。

于 2013-09-09T04:59:21.093 に答える
6

更新:より良いアプローチについては、同じスレッドの Blackus の回答を参照してください。


JavaScript と Regex の使用に抵抗がない場合は、以下のソリューションを使用して、属性内のすべてのプロパティwidthとプロパティを検索し、それらを何も検索しないでください。heightstylereplace

//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); 
于 2013-09-09T05:38:08.173 に答える
2
$("#sample_id").css({ 'width' : '', 'height' : '' });
于 2013-09-09T04:59:49.017 に答える
1

幅要素と高さ要素に auto を指定することは、技術的にはそれらを削除することと同じです。バニラ Javascript を使用する:

images[i].style.height = "auto";
images[i].style.width = "auto";
于 2019-09-19T03:45:36.790 に答える
0

このように使うだけ

 $("#sample_id").css("width", "");
 $("#sample_id").css("height", "");
于 2013-09-09T04:56:41.660 に答える