Le tableau ci-dessous présente certains types de classes.
Je voudrais changer la cellule de couleur 1 et 2 en cliquant, cela signifie que la couleur n'est modifiée que si aucune couleur d'arrière-plan n'est définie dans chaque cellule.
Existe-t-il une méthode pour cela? Merci
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <td id="1">1</td> <td id="aqua">2</td> <td id="green">3</td> </table>
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
$(function() {
$("td").click(function() {
$(this).css('background-color','yellow');
});
});
4 Réponses :
Dans le gestionnaire d'événements de clic, vérifiez d'abord si l'élément a une couleur définie et changez la couleur uniquement si elle ne répond pas à vos critères requis. Vous pouvez utiliser $ (this) .css ('background-color') pour obtenir la couleur actuelle.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <td id="1">1</td> <td id="aqua">2</td> <td id="green">3</td> </table>
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color: green;
}
$(function() {
$("td").click(function() {
if ($(this).css('background-color') === 'rgba(0, 0, 0, 0)') {
$(this).css('background-color', 'yellow')
}
});
});
Vous pouvez ajouter une classe qui lui donnera le style background: yellow . de cette façon chaque fois qu'une autre couleur lui est donnée par id, le style de sélecteur id aura la priorité bien que la classe;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <td id="1">1</td> <td id="aqua">2</td> <td id="green">3</td> </table>
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
.default-yellow {
background-color: yellow;
}
$(function() {
$("td").click(function() {
$(this).addClass('default-yellow');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <td id="1">1</td> <td id="aqua">2</td> <td id="green">3</td> </table>
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
.test{background:yellow;}
$(function() {
$("td").click(function() {
$(this).addClass('test');
});
});
Vous pouvez vérifier si l'élément a une couleur d'arrière-plan transparente
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <td id="1">1</td> <td id="aqua">2</td> <td id="green">3</td> </table>
#aqua {
border-bottom: 3px solid aqua;
}
#green {
background-color:green;
}
$(function() {
$("td").click(function() {
if ($(this).css('background-color') == 'rgba(0, 0, 0, 0)') {
$(this).css('background-color','yellow');
};
});
});
Cela peut être utile stackoverflow.com/questions/11517150/...