[英]How to change the css of div programmatically?
我正在使用具有某些內聯樣式的div,而且我正在使用一個類來覆蓋內聯樣式。 單擊按鈕時,我需要更改div的邊框。 我使用了以下代碼,但是不起作用?
HtML代碼:
<div id="test2" class="test" style="height:30px; width:150px; background-color:red; border:1px solid green;"></div>
<button id="test1">Test</button>
班級風格
div.test{
border:2px solid black !important;
background-color:blue !important;
}
按鈕代碼
$('#test1').click(function(){
$('#test2').css('border','none !important');
});
演示 :有關演示,請單擊此處 。
請提供一些建議以更改元素的css。
除了Kartikeya的注釋,即您不能在jQuery的.css
方法中使用!important
,因為該方法應用了內聯樣式,因此,由於您在此處使用!important
,因此樣式不會被覆蓋:
div.text {
border:2px solid black !important;
}
我建議您簡單地刪除!important
(過度使用此方法被認為是不好的做法)。 如果您不願意這樣做,則另一種可能性是使用.toggleClass
方法刪除並添加沒有邊框的方法。 但是正如我已經說過的那樣,這是不太可取的,因為除非絕對必要,否則應避免!important
。
另外,值得注意的是,由於盒子模型以及元素占用空間的方式,當刪除邊框時,元素會物理收縮。 要阻止這種情況發生,請不要將邊框設置為none
,而應將其設置為transparent
。
為您的樣式更改添加另一個類:
div.test_borderless{
border:none !important;
background-color:blue !important;
}
然后使用removeClass()
和addClass()
交換樣式:
$('#test1').click(function(){
$('#test2').removeClass("test").addClass("test_borderless");
});
更新的提琴: http : //jsfiddle.net/r28h4vws/6/
您可以刪除現有的類test
然后添加僅指定background-color
class test2
div.test2{
background-color:blue !important;
}
$('#test1').click(function(){
$("#test2").removeClass("test").addClass("test2")
});
從jquery和CSS的邊框中刪除!Important:
的HTML
<div id="test2" class="test" style="height:30px; width:150px; background-color:red; border:1px solid green;"></div>
<button id="test1">Test</button>
的CSS
div.test{
border:2px solid black;
background-color:blue !important;
}
Java腳本
$('#test1').click(function(){
$('#test2').css('border','none');
});
這是一個有效的更新: http : //jsfiddle.net/r28h4vws/7/
<script>
var style = $("#test2").attr("style");
//Write code to remove css of border here like following.
style = style.replace("border:1px solid green;","");
$("#test2").attr("style", style+"border:none !important;");
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.