繁体   English   中英

如何以编程方式更改div的CSS?

[英]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") 
});

jsfiddle

从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM