将类添加到元素 [英] Add class to element

查看:119
本文介绍了将类添加到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样,我有两个标签,所以当我点击一个它是活跃的,逻辑。现在我试图区分活跃和非活动标签,但不是与.css属性,但我想添加特定的类点击标签,像这样:

Like this, I have two tabs, so when i click on one it's active, logic. Now im trying to make difference between active and inactive tab, but not with .css property, but I wanna' add specific class to clicked tab, like this:

$(".tab1").addClass('active');

但没有好处。还要记住我使用外部css文件。

but, no good. Also have in mind that I'm using external css file.

<div id="menuitem" class="tab1"></div>
<div id="menuitem" class="tab2"></div>

.active {
    width: 170px;
    height: 70px;
    float: right;
    background-color: red;
}

#menuitem {
    width: 170px;
    height: 70px;
    float: right;
    background-color: white;
}


推荐答案

在不同的元素上使用相同的 id id 必须是唯一的,并尝试:

First of all don't use same id on different elements, id's must be unique and try this:

jQuery:

$('.menuitem').click(function() {
    $('.menuitem').removeClass('active');
    //removes active class from all menu items

    $(this).addClass('active');
    //adds active class to clicked one
});

html:

<div id="tab1" class="menuitem"></div>
<div id="tab2" class="menuitem"></div>

css:,您不需要为活动类定义相同的属性,只是定义区别:

css: you don't need to define same properties to active class, just define the difference:

.active { background-color: red; }

.menuitem {
  width: 170px;
  height: 70px;
  float: right;
  background-color: white;
}

这篇关于将类添加到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆