将样式应用于特定的body类

时间:2014-03-03 12:24:28

标签: javascript jquery

我需要在身体的特定类中应用额外的“margin-top”。此类的名称已在CSS文件中,并显示为:

html body.admin-menu {
   margin-top:29px !important;
}

但是,我需要在jQuery中添加一个位置才能将此margin-top更改为60px。

我尝试了这4种没有雪茄的选择:

$('html body.admin-menu').addClass('marginfix');

$('html body.admin-menu').attr('style', 'margin-top:60px !important');

$('html body.admin-menu').attr('style', function(i,s) { return s + 'margin-top: 60px !important;' });

$('<style>.marginfix { margin-top:60px !important; }</style>').appendTo('html body.admin-menu');

我唯一可以影响的元素是“html”,但我需要将这种风格应用于这个非常具体的案例(html body.admin-menu),而不仅仅是“html”标签。

任何人都知道什么会起作用?

3 个答案:

答案 0 :(得分:1)

不确定,但在我看来,你错过了doc ready方法。您似乎在准备好之前将该类添加到元素中。

这应该有效:

$(function(){
    $('html body.admin-menu').addClass('marginfix');
});

或试试这个:

$(function(){
    $('html body.admin-menu').css({marginTop: '60px'});
}); // above code will make a inline css to the body.

尝试将其包装在doc ready方法中,我猜你的css文件中的css类.marginfix的样式。虽然您可以省略选择器中的html

这个css应该是这样的:

html body.admin-menu {
   margin-top:29px !important;
}

.marginfix{
    margin-top:60px !important; // this overrides above class applied to body.
}

答案 1 :(得分:0)

试试这个:

$('body.admin-menu').css({'margin-top':'60px'});

并从CSS中删除!important。只需在所有其他CSS之后添加body.admin-menu部分,即可覆盖之前的任何样式。

答案 2 :(得分:0)

您可以执行类似操作,将样式添加到<head>

$('<style type="text/css">.marginfix { margin-top:60px !important; }</style>').appendTo($('head'));

然后,您调用addClass()方法:

$('body.admin-menu').addClass('marginfix');