JavaScript中单元格背景颜色的比较
根据表格单元格的当前颜色,我正在尝试更改颜色,或者在鼠标离开单元格时保持不变。这是我的剧本:JavaScript中单元格背景颜色的比较,javascript,Javascript,根据表格单元格的当前颜色,我正在尝试更改颜色,或者在鼠标离开单元格时保持不变。这是我的剧本: <script> $('.tableCell') .mouseenter(function () { $(this).find(".hideCheckBox").show(); }) .mouseleave(function () { $(this).find(".hideC
<script>
$('.tableCell')
.mouseenter(function () {
$(this).find(".hideCheckBox").show();
})
.mouseleave(function () {
$(this).find(".hideCheckBox").hide();
if ($(this).find(".hideCheckBox").is(":checked")) {
$(this).css("backgroundColor", "#10657e");
$(this).css("color", "white");
}
else {
if ($(this).style.backgroundColor === "#157fa0") {
} else {
$(this).css("backgroundColor", "white");
$(this).css("color", "black");
}
}
});
</script>
尝试比较RGB值:
if ($(this).style.backgroundColor == 'rgb(21, 127, 160)') {
尝试比较RGB值:
if ($(this).style.backgroundColor == 'rgb(21, 127, 160)') {
问题 问题是不同的浏览器可能以不同的方式报告颜色。例如,您可以将颜色设置为
#ff0000
,但当您要求它时,您会得到rgb(255,0,0)
解决方法
比较背景色最安全的方法是创建一个临时元素,该元素的颜色与要比较的颜色相同。然后,检索temp元素的颜色,并将该颜色与您实际感兴趣的元素的颜色进行比较。当单元测试指令修改元素上的颜色时,我们使用这种解决方法
示例(使用jQuery)
var getExpectedColor=函数(颜色){
//这是必要的,因为浏览器对颜色的表示可能与您设置的不同。
//例如,您可以将颜色设置为#ff0000,当您要求时,返回rgb(255,0,0)。
变量温度=$('');
$('body')。追加(临时);
var expected=temp.css('background-color',color.).css('background-color');
移除温度();
预期收益;
};
if($(this.css('background-color')==getExpectedColor('157fa0')){
//宾果游戏
}
问题
问题是不同的浏览器可能以不同的方式报告颜色。例如,您可以将颜色设置为#ff0000
,但当您要求它时,您会得到rgb(255,0,0)
解决方法
比较背景色最安全的方法是创建一个临时元素,该元素的颜色与要比较的颜色相同。然后,检索temp元素的颜色,并将该颜色与您实际感兴趣的元素的颜色进行比较。当单元测试指令修改元素上的颜色时,我们使用这种解决方法
示例(使用jQuery)
var getExpectedColor=函数(颜色){
//这是必要的,因为浏览器对颜色的表示可能与您设置的不同。
//例如,您可以将颜色设置为#ff0000,当您要求时,返回rgb(255,0,0)。
变量温度=$('');
$('body')。追加(临时);
var expected=temp.css('background-color',color.).css('background-color');
移除温度();
预期收益;
};
if($(this.css('background-color')==getExpectedColor('157fa0')){
//宾果游戏
}
为什么不直接使用CSS?看看console.log($(this.style.backgroundColor)
作为一个起点,我真的不喜欢CSS,也许这会是一个更好的想法HTML、CSS和js在网页上齐头并进。尽管您可以用JS编写所有内容,而不必使用html、css,但如果您愿意,正确使用所有3种格式只会使所有内容更简单、更美观。但是可以,打开控制台并检查值。使用hasClass
、addClass
和removeClass
会更容易。为什么不直接使用CSS呢?看看console.log($(this.style.backgroundColor)
作为一个起点,我真的不喜欢CSS,也许这会是一个更好的想法HTML,CSS和JS在网页上齐头并进。尽管您可以用JS编写所有内容,而不必使用html、css,但如果您愿意,正确使用所有3种格式只会使所有内容更简单、更美观。但是可以,打开控制台并检查值。使用hasClass
、addClass
和removeClass
会更容易。并使用CSS而不是JS设置该类的样式。
var getExpectedColor = function(color) {
// This is necessary because the browsers representation of a color may be different than what you set.
// For instance, you maybe set the color to #ff0000, and when you ask for it, get back rgb(255, 0, 0).
var temp = $('<div>');
$('body').append(temp);
var expected = temp.css('background-color', color).css('background-color');
temp.remove();
return expected;
};
if ($(this).css('background-color') === getExpectedColor('#157fa0')) {
// bingo
}