JQuery - AddClass o RemoveClass - ¿Existe una clase de anexo?
-
19-09-2019 - |
Pregunta
Tengo CSS desplazando las imágenes para mis pestañas y estoy tratando de que la clase cambie de. Cómo .wow_on cuando hago clic en la imagen cómo.
Mis pestañas son
Cómo | Que | Cuando | Quien | POR QUÉ
Tengo clases para cada (.wow, .wow_on), (.what, .what_on), etc ...
¿Puedo hacer jQuery agregar _on al nombre de clase original usando Click (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");
}
Solución
ACTUALIZADO:
Prueba esto:
$('.tabs a').click(function() {
$('.tabs a').removeAttr('id'); // remove all ids
$(this).attr('id', this.className + "_on") // create how_on as this id.
});
Estás usando el nombre de clase para crear una identificación única. Logrará lo mismo que estás tratando de hacer. Aquí hay una muestra con "por qué" seleccionado.
<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>
Por supuesto, La forma más simple es agregar la clase .HOW_ON y tener ambas clases.
<div class='how how_on'>some stuff</div>
No hay nada de malo en eso y puede anular fácilmente los estilos o apuntar al elemento.
.how { color: #000; }
div.how_on { color: #F00; } /* increased specificity */
Si desea asegurarse de que lo anule, aumente la especificidad.
Otros consejos
Cuando usas addClass
, agrega/agrega una clase a menos que elimine algunos primero usando removeClass
, entonces te gusta esto:
$('.how_on').mouseover(function(){
$(this).removeClass('class_name').addClass('class_name');
});
$('.why').mouseover(function(){
$(this).removeClass('class_name').addClass('class_name');
});
// and so on.........
Desearía que JQuery tuviera eso, pero por lo que puedo decir no. Siempre puedes usar removeClass
para deshacerse de una versión y addClass
Para agregar el otro. Alternativamente, puede cocinar su propio pequeño complemento. Parece algo útil para hacer; Incluso JQuery UI tiene que lidiar con todas sus clases ("UI-State-Default", "UI-State-Hover", etc.) y sería más fácil si pudiera llamar a una API para actualizar la vástago de clase "UI" -Tate- "con un sufijo elegido.
Por lo tanto, la forma simple de jQuery de hacerlo en su caso sería algo así:
// 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);
}
Entonces llamarías turnOn("how")
Cuando desea la pestaña "Cómo" cambiar a la clase "How_on", y turnOff("how")
Para que pase de "How_on" a "Cómo".
.addClass( function(index, class) )
AddClass toma una función anónima y puede agregar la lógica para agregar la clase aquí
me gusta
$('ELEMENT SELECTION').addClass(function() {
return $(this).attr("class") + 'CLASS TO BE ADDED';
});
siempre puedes hacer:
jQuery(".tabs a").click(function(){
this.className += '_on';
}
que agregará el sufijo deseado.
Aún mejor será agregar la clase de "activación" a la 'li' que contiene.
jQuery(".tabs a").click(function(){
$(this).parent().toggleClass('on');
}
Y tu CSS debería verse así:
/* 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;
}
y puede definir un comportamiento general para su enlace de pestañas esto
.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 */ }
Puedes Reemplace completamente su parte jQuery con este;
¡Esto debe funcionar como se esperaba!
Parte de JavaScript
$(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 esto ayude!
Saludos
Hay algunos enfoques.
- Eliminar la clase, agregar
_on
a la cadena y agregue la nueva clase. - Simplemente diseña tu
*_on
clases para modificar los estilos de clases originales. Entonces todo lo que tienes que hacer es eliminar el*_on
clase para volver al estilo antiguo.
¿Por qué no agregas la clase? on
a los elementos en cuestión y cambiar sus reglas de CSS de .how and .how_on
a .how and .how.on
?
Entonces, en tu .how.on
puedes anular cualquier cosa establecida en el .how
que quieres cambiar.
No creo que necesite doblar JavaScript/jQuery a su voluntad, más bien usar la especificidad CSS para lo que estaba destinado.