Pergunta

Eu tenho o css pairando sobre imagens para minhas guias e estou tentando fazer com que a classe mude de .Como para .ow_on quando clico na imagem como.

Minhas guias são

Como | O que | Quando | Quem | POR QUÊ

Eu tenho aulas para cada um (. Como.

Posso fazer o jQuery adicionar _on ao nome da classe original usando clique (function () {}); ?

Html:

<div id="tab_container">
     <ul class="tabs">
        <li><a class="how_on" href="#how">How</a></li>
        <li><a class="why" href="#why">Why</a></li>
        <li><a class="what" href="#what">What</a></li>
        <li><a class="who" href="#who">Who</a></li>
        <li><a class="when" href="#when">When</a></li>
    </ul>
    <p><img src="images/tab_top.jpg" width="864px" height="6px" alt="" border="0" /></p>
</div>
<div class="tab_body">
    <!-- HOW -->
        <div id="how" class="tab">
            <strong>HOW IT WORKS:</strong>
        </div>

JQuery:

<script type="text/javascript">
jQuery(document).ready(function(){
 //if this is not the first tab, hide it
 jQuery(".tab:not(:first)").hide();
 //to fix u know who
 jQuery(".tab:first").show();
 //when we click one of the tabs
 jQuery(".tabs a").click(function(){
 //get the ID of the element we need to show
 stringref = jQuery(this).attr("href").split('#')[1];




 // adjust css on tabs to show active tab





 //hide the tabs that doesn't match the ID
 jQuery('.tab:not(#'+stringref+')').hide();
 //fix
 if (jQuery.browser.msie && jQuery.browser.version.substr(0,3) == "6.0") {
 jQuery('.tab#' + stringref).show();
 }
 else
 //display our tab fading it in
 jQuery('.tab#' + stringref).fadeIn();
 //stay with me
 return false;
 });

});
</script>

CSS:

.tabs
{
    width: 683px;
    height: 29px;
    padding: 0;
    margin: 0;
    display: inline;
    float: left;
    overflow: hidden;
    list-style-type: none;
}

.tabs li
{
    margin: 0;
    padding: 0;
    display: inline;
    float: left;
}

.tabs  a {  background-position: 0 -58px;}
.tabs .on a {   background-position: 0 -29px;}

.how,
a.how:link,
a.how:visited
{
  float: left;
  display: inline;
  width: 135px;
  height: 29px;
  margin: 0;
  text-decoration: none;
  text-indent: -99999px;
  overflow: hidden;  
  background-image: url("../images/how_tab.jpg");
}
Foi útil?

Solução

ATUALIZADA:

Experimente isso:

$('.tabs a').click(function() {
    $('.tabs a').removeAttr('id'); // remove all ids
    $(this).attr('id', this.className + "_on") // create how_on as this id.
});

Você está usando o nome da classe para criar um ID exclusivo. Isso realizará a mesma coisa que você está tentando fazer. Aqui está uma amostra com "por que" selecionado.

 <ul class="tabs">
    <li><a class="how" href="#how">How</a></li>
    <li><a id='why_on' class="why" href="#why">Why</a></li>
    <li><a class="what" href="#what">What</a></li>
    <li><a class="who" href="#who">Who</a></li>
    <li><a class="when" href="#when">When</a></li>
 </ul>

É claro, A maneira mais simples é adicionar a classe .ow_on e ter as duas classes.

<div class='how how_on'>some stuff</div>

Nada de errado com isso e você pode substituir facilmente os estilos ou direcionar o elemento.

.how { color: #000; }
div.how_on { color: #F00; } /* increased specificity */

Se você deseja garantir que ele substitua, aumente a especificidade.

Outras dicas

Quando você usa addClass, ele adiciona/anexa uma aula, a menos que você remova alguns primeiro usando removeClass, então você gosta disso:

$('.how_on').mouseover(function(){
    $(this).removeClass('class_name').addClass('class_name');
});

$('.why').mouseover(function(){
    $(this).removeClass('class_name').addClass('class_name');
});

// and so on.........

Eu gostaria que a JQuery tivesse isso, mas até onde eu sei, não. Você sempre pode usar removeClass para se livrar de uma versão e addClass para adicionar o outro. Como alternativa, você pode cozinhar seu próprio plug -in. Parece uma coisa útil a fazer; Até a interface do usuário do jQuery tem que lidar com o MUNGING todas as suas aulas ("UI-State-Default", "Ui-State Wover" etc.) e seria mais fácil se pudesse chamar uma API para atualizar a classe "UI -state- "Com um sufixo escolhido.

Assim, a maneira simples de fazer isso no seu caso seria algo como:

// to go from "foo" to "foo_on":
function turnOn(which) {
  $('.tabs').find('a.' + which)
    .removeClass(which)
    .addClass(which + '_on');
};

// to go from "foo_on" to "foo"
function turnOff(which) {
  $('.tabs').find('a.' + which + '_on')
    .removeClass(which + '_on')
    .addClass(which);
}

Você então ligaria turnOn("how") Quando você deseja que a guia "Como" mude para a classe "How_on", e turnOff("how") Para fazê -lo ir de "How_on" para "Como".

.addClass( function(index, class) )

Addclass pega uma função anônima e você pode adicionar a lógica para anexar a classe aqui

Curti

$('ELEMENT SELECTION').addClass(function() {
  return $(this).attr("class") + 'CLASS TO BE ADDED';
});

Você sempre pode fazer:

jQuery(".tabs a").click(function(){
    this.className += '_on';
}

o que adicionará o sufixo desejado.

Melhor ainda será adicionar a classe "Ativação" à contenção de 'Li'.

jQuery(".tabs a").click(function(){
    $(this).parent().toggleClass('on');
}

E seu CSS deve ficar assim:

/* here i removed the 'a.how_on' entry */
.how,
a.how:link,
a.how:visited
{
  float: left;
  display: inline;
  width: 135px;
  height: 29px;
  margin: 0;
  text-decoration: none;
  text-indent: -99999px;
  overflow: hidden;  
}

a.how:visited, a.how:link, a.how:hover
{
    background-image: url("../images/how_tab.jpg");
    background-position: 0 -58px;
}

/* this will cause the link to behave different when its parent is of class on */
.on a.how
{
    background-image: url("../images/how_tab.jpg");
    background-position: 0 -29px;
}

e você pode definir um comportamento geral para suas guias vincular isso

.tabs a { /* style */ }
.tabs a:link { /* link style */ }
.tabs a:hover { /* hover style */ }

.tabs .on a { /* activated style */ }
.tabs .on a:link { /* activated link style */ }
.tabs .on a:hover { /* activated hover style */ }

Você pode Substitua completamente sua parte do jQuery com isso;

Isso deve funcionar como esperado!

Javascript Part

$(function() {

    var tabs = $('div.tab_body > div.tab');
    tabs.hide().filter(':first').show();

    $('div#tab_container ul.tabs a').click(function() {
        tabs.hide();
        var myhash = this.hash.split('#')[1];

        tabs.filter(this.hash).show();

        $('a:not(.' + myhash + '_on)').each(function() {
            var h = this.hash.split('#')[1];
            $(this).removeClass(h + '_on').addClass(h);
        });
        $(this).removeClass(myhash).addClass(myhash + '_on');

        return false;
    }).filter(':first').click();
});

Parte html

<div id="tab_container">
 <ul class="tabs">
    <li><a class="how" href="#how">How</a></li>
    <li><a class="why" href="#why">Why</a></li>
    <li><a class="what" href="#what">What</a></li>
    <li><a class="who" href="#who">Who</a></li>
    <li><a class="when" href="#when">When</a></li>
</ul>            
</div>

<div class="tab_body">
    <div id="how" class="tab">
        <strong>how</strong>
    </div>
    <div id="why" class="tab">
        <strong>why:</strong>
    </div>
    <div id="what" class="tab">
        <strong>what</strong>
    </div>
    <div id="who" class="tab">
        <strong>who</strong>
    </div>
    <div id="when" class="tab">
     <strong>when</strong>
    </div>
  </div>

Espero que isso ajude!

Cumprimentos

Existem algumas abordagens.

  1. Remova a aula, anexa _on à string e adicione a nova classe.
  2. Simplesmente projete o seu *_on Classes para modificar os estilos de classes originais. Então tudo o que você precisa fazer é remover o *_on classe para reverter para o estilo antigo.

Por que você não apenas adiciona a aula on para os elementos em questão e alterar suas regras CSS de .how and .how_on para .how and .how.on?

Então, em seu .how.on Você pode apenas substituir qualquer coisa definida no .how que você quer mudar.

Eu não acho que você precise dobrar o JavaScript/jQuery para sua vontade, use a especificidade do CSS para o que ele era feito.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top