我目前缺少有关querySelectorAll在我的代码中如何工作的信息。我使用它来遍历并在表中设置所有tds的事件侦听器,以便获取对单击的任何td的引用,以便我只能修改该td。但是,在实现辅助功能时,遇到了一个我不了解的问题。看起来,即使每个td都有一个类,并且通过CSS为该类提供了背景颜色样式,除非我手动设置了该值(通过我的paintColor函数),否则该值仍被视为空白。 Console.log显示该值在明确设置之前为空。为什么?
谢谢
HTML
<table class="table">
<!-- Row 1 -->
<tr class="row">
<td class="cell"></td>
<td class="cell"></td>
<div class="menus">
<div class="menu-left">
<input type="checkbox" id="eye-check" unchecked/>
<span>Eyedropper</span>
<table class="eye-table">
<td class="eye-cell">
<span class="tooltip">Hexidecimal value of selected eyedropper
color.</span>
</td>
</table>
<div class="menu-left-text">
<p class="eye-text">rgb(255,255,255)</p>
</div>
</div>
CSS
.cell {
border: 1px solid lightgrey;
/* box-shadow: 1.5px 1.5px 1.5px lightgrey; */
background-color: #ffffff;
width: 16px;
height: 16px;
cursor: crosshair;
z-index: 4;
}
JS
// Gloabal Variables
let cells = document.querySelectorAll(".cell");
let activeColor = "rgb(255,255,255)";
let table = document.querySelector("table.table");
let activeCell = document.querySelector(".cell");
let dropper;
let eyeCell = document.querySelector(".eye-cell");
let eyeText = document.querySelector(".eye-text");
// Listen for EyeDropper
document.querySelector("#eye-check").addEventListener("click", evt =>{
dropper = document.querySelector("#eye-check");
if (dropper.checked) {
// Set Dropper Indicator on Table Border
table.style.border = "5px dashed black";
} else {
// Set Paint Indicator on Table Border
table.style.border = "5px solid silver";
}
});
// Listen for Clicks
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", evt => {
activeCell = cells[i];
// Check for EyeDropper Toggle
checkDropper();
});
}
// Check for Eye Dropper Checked
function checkDropper() {
dropper = document.querySelector("#eye-check");
if (dropper.checked) {
activateDropper();
} else {
activatePaint();
}
}
// Dropper is Active, Activate Dropper
function activateDropper() {
// Set EyeDropper Color
eyeCell.style.backgroundColor = activeCell.style.backgroundColor;
// Set Text Value
eyeText.innerHTML = activeCell.style.backgroundColor.replace(/\s
/g,"");}
// Dropper is Inactive, Activate Painting
function activatePaint() {
// Get Active Color
getActiveColor();
// Paint Color into Cell
paintColor();
}
// Get Brush Color
function getActiveColor() {
activeColor = document.querySelector("#brush-color").value;
}
// Paint Color into active cell
function paintColor() {
activeCell.style.backgroundColor = activeColor;
}
点击here
答案 0 :(得分:0)
我相信这里发生的事情是Node对象没有显式设置样式,这就是为什么访问obj.style.whatever时得到空字符串的原因。 HTML Node对象和CSS是独立的实体,并且CSS告诉浏览器(而不是Node)更改其样式。如果将CSS内联设置在元素上,则在按您的方式访问它时应显示它。
请参见此处:http://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style