我使用 HTML、CSS 和 javascript 编写了一个简单的四连线游戏。该游戏在 Chrome 中功能齐全,但在使用 Firefox 浏览器时出现一些有趣的行为。
在 Firefox 中,当玩家放下棋子时,游戏板的颜色会成功改变,但是,当我在检查玩家是否获胜时进行比较操作时,Firefox 不会检测到任何颜色。
我试图通过声明一个特定的 rgb 值来解决这个问题,而不是仅仅说“紫色”,我做了类似下面的事情,结果相似。
这里只是我的 javascript 代码的相关部分:
const _purple = "rgb(124, 0, 132)";
columns[id][5 - pcs[id]].style.background = _purple; // assignment works always
columns[id][5 - pcs[id]].style.background = 'green'; // assignment like this ok too
if (columns[_col][_row].style.background == _purple) // only works in Chrome
if (columns[_col][_row].style.background == 'green') // only works in Chrome
我也尝试按照 friend 的建议使用 ===
。
***** 更新 ***** 我检查了控制台,看看 Firefox 返回了什么,正如第一条评论中所建议的那样,Firefox 似乎返回了正确的值。
rgb(124, 0, 132) none repeat scroll 0% 0%
green none repeat scroll 0% 0%
但是比较操作永远不会返回 true。 我试图只使用整个字符串,但是 也没有用。
不出所料,在 Chrome 上,如果我只是使用
“rgb(124, 0, 132)”
而不是 _purple
它也返回 true。
如果对解决这个问题有帮助 我在中使用的 CSS 元素 游戏板是:
.box {
background: white;
border: 2px solid black;
}
进一步:
visual studio 向我报告“类型字符串上不存在属性颜色”。调用 console.log(first.style.background.color);
在我的 Firefox 控制台中返回 undefined
,而调用 console.log(second. style.background);
返回正确的 rgb 值。当比较未定义的 .color
值时它返回 true
,但是当比较 .background 属性时它返回 false
,这确实是 rgb 值
感谢您对这个问题的任何帮助,可以在此处查看游戏和纠正此错误的尝试 https://github.com/paolo-Rancati/four_in_a_sequence/tree/main/snippet
最佳答案
您可以使用 computedStyle
解决这个问题,显然您的 rgb 值 "rgb(124, 0, 132)"
与 FireFox 用于 紫色
。
const _purple = "rgb(128, 0, 128)";
let first = document.getElementById("first");
let second = document.getElementById("second");
const spaces = document.querySelectorAll('.box');
first.style.background = "purple";
second.style.background = _purple;
console.log(window.getComputedStyle(first).backgroundColor);
console.log(window.getComputedStyle(second).backgroundColor);
console.log(window.getComputedStyle(first).backgroundColor === window.getComputedStyle(second).backgroundColor);
div {
width: 100%;
height: 50px;
border: 1px solid black;
}
.box {
background: white;
border: 2px solid black;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"></html>
<head>
<link rel="stylesheet" href="static/website.css">
<meta charset="utf-8" />
<title>Game Page</title>
</head>
<div id="first"></div>
<div id="second"></div>
</html>
关于javascript - Firefox 在比较操作中未检测到 rgb 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69872081/