我有一个函数,当我传入这个函数(‘黄色’,‘蓝色’)时,它工作得很好。单击“更改颜色”,再次单击“更改”。但是如果我通过了(' #404040 ',‘蓝色’),它只工作一次,颜色变为#404040,但如果我再次点击,什么也不会发生。
我不知道为什么会这样,在我看来一切都很好。有谁能帮上忙吗?
JavaScript:
function changeColor(bgColor, textColor) {
var textClassElements = document.getElementsByClassName("textClass");
var spanColor = document.getElementById("spanColor");
spanColor.style.background = bgColor;
if (document.body.style.background != bgColor) {
document.body.style.background = bgColor;
for (var i = 0; i < textClassElements.length; i++) {
textClassElements.item(i).style.color = textColor;
}
}
else{
document.body.style.background = 'red';
spanColor.style.background = 'red';
for (var i = 0; i < textClassElements.length; i++) {
textClassElements.item(i).style.color = textColor;
}
}
};HTML:
<li class="list-3"><a style="cursor: pointer;" onclick="changeColor('#404040', 'blue');">MUDA TEMA</a></li>发布于 2020-12-24 06:37:25
我解决了我自己的问题。就像@DaveB说的,黄色返回黄色,所以if和else工作得很好,而十六进制颜色不返回" hex“,所以它永远不会进入else……
所以,我所做的是放置一个标志,这个标志需要在函数之外,否则每次我们单击函数时,标志都会是false…
代码如下:
var flag=false;
function changeColor(bgColor, textColor) {
var textClassElements = document.getElementsByClassName("textClass");
var spanColor = document.getElementById("spanColor");
spanColor.style.background = bgColor;
if (flag == false) {
flag=true;
document.body.style.background = bgColor;
for (var i = 0; i < textClassElements.length; i++) {
textClassElements.item(i).style.color = textColor;
}
}
else{
document.body.style.backgroundColor = 'red';
for (var i = 0; i < textClassElements.length; i++) {
textClassElements.item(i).style.color = textColor;
}
flag=false;
}
};发布于 2020-12-24 03:55:47
问题出在以下代码行中:
if (document.body.style.background != bgColor) {
当document.body.style.background设置为yellow时,document.body.style.background返回yellow。
但是,当document.body.style.background设置为#404040时,读取属性document.body.style.background的调用将返回'rgb(64, 64, 64)',因此if的结果始终为true,因此颜色永远不会再次更改。
最好在Javascript中避免使用颜色逻辑,而应将其保存在CSS类中,该类可以读取或写入您希望更改的元素。
发布于 2020-12-24 06:55:11
通过添加和删除类,您可以切换颜色和其他样式。我建议使用!重要的是css总是覆盖旧的css
<!DOCTYPE html>
<html>
<head>
<style>
.overwritecolor{
background-color: #000 !important;
color: #fff !important;
}
</style>
</head>
<body>
<ul>
<li class="list-3">
<a style="cursor: pointer;" onclick="changeColorTo();">MUDA TEMA</a>
</li>
</ul>
<script>
var isB = true;
function changeColorTo(){
var objects = new Array;
objects.push('body', 'a');//use # for id's and . for class
if(window.isB){
for(var i=0;i<objects.length;i++){
var obj = document.querySelectorAll(objects[i]);
for(var x=0;x<obj.length;x++){
obj[x].classList.add('overwritecolor');
}
}
window.isB = false;
}else{
for(var i=0;i<objects.length;i++){
var obj = document.querySelectorAll(objects[i]);
for(var x=0;x<obj.length;x++){
obj[x].classList.remove('overwritecolor');
}
}
window.isB = true;
}
}
</script>
</body>
</html>https://stackoverflow.com/questions/65429088
复制相似问题