如何通过jQuery if语句编辑CSS类

时间:2013-09-03 15:47:57

标签: jquery css if-statement

我有一个if语句检查“ivnt”的url,我希望div“carriage-promo”的高度从0px的dafault变为40px。

我不想添加一个类或删除一个类,我知道如何实现这个目标并且它不能解决这个问题我害怕。

考虑:

$(document).ready(function () {
 if(window.location.href.indexOf("invt") > -1) { 
    $('#promo-carriage').css{
          height: '40px'}
         }
      });

然而,这对我不起作用。有什么建议?我很确定这会是一个语法错误,但我是jQuery / JS的新手!

4 个答案:

答案 0 :(得分:2)

总之,只要您只传递一个键+值对,就可以将其传递为:

$(element).css("attribute","value");

如果您想传递多个声明,请使用对象

$(element).css({height:"200px", width:"100px", backgroundColor: "red"});$(element).css({height:"200px"});

请注意两个示例之间的差异。在对象中,您可以或不在引号内定义键,但最好是使用没有引号的javascript定义,其中“background-color”变为backgroundColor: 语法也会改变。请注意,在对象中,您使用双冒号分隔键和值:使用逗号分隔不同的对。

有关详细信息,请参阅http://api.jquery.com/css/

答案 1 :(得分:1)

在引号内使用parenteses .css()height

$(document).ready(function () {
    if(window.location.href.indexOf("invt") > -1) {
        $("#promo-carriage").css("height", "40px");
    }
});

答案 2 :(得分:1)

您在css方法后缺少左括号:

$('#promo-carriage').css({

但是,如果您试图隐藏/显示某些内容,我建议不要使用height属性来执行此操作。您想使用CSS display属性。

有快速jQuery方法可以更改对象的显示:

$("#promo-carriage").toggle()
$("#promo-carriage").hide()
$("#promo-carriage").show()

这是一个快速简便的jsFiddle example

答案 3 :(得分:0)

{P} ''我猜错了height,另一种可能是直接使用height method

$(document).ready(function () {
 if(window.location.href.indexOf("invt") > -1) { 
    $('#promo-carriage').height('40px');
      });