我正在尝试创建一个鼠标事件,允许用户使用" ctrl"来绘制红色或蓝色。键和shift键,并有一个按钮,如果用户想要擦除窗口,但加载页面时没有任何事情发生。我的控制台也没有任何错误。我不知道我错过了什么。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Erase Drawing Window</title>
<style>
table
{
width: 400px;
border-collapse:collapse;
}
td
{
width: 4px;
height: 4px;
}
</style>
<script src = "draw.js">
</script>
</head>
<body>
<table id = "canvas">
<caption>Hold <em>Ctrl</em> (or <em>Control</em>) to draw blue.
Hold <em>Shift</em> to draw red.</caption>
<tbody id = "tablebody"></tbody>
</table>
<script src = "draw.js">
function createCanvas()
{
var side = 100;
var tbody = document.getElementById( "tablebody" );
for ( var i = 0; i < side; ++i )
{
var row = document.createElement( "tr" );
for ( var j = 0; j < side; ++j )
{
var cell = document.createElement( "td" );
row.appendChild( cell );
}
tbody.appendChild( row );
}
document.getElementById( "canvas" ). addEventListener(
"mousemove", processMouseMove, false );
}
function processMouseMove( e)
{
if (e.target.tagName.toLowerCase() == "td" )
{
if ( e.ctrlKey )
{
e.target.setAttribute( "class", "blue" );
}
if ( e.shiftKey )
{
e.targetsetAttribute ( "class", "red" );
}
}
}
window.addEventListener( "load", createCanvas, false );
console.log('You entered', x);
function erase()
{
var tb=document.getElementsByTagName('table');
var tbc=tb[0].getElementsByTagName('td');
for(k=0;k<tbc.length;k++){tbc[k].style.backgroundColor='pink'}
}
</script>
</body>
答案 0 :(得分:0)
我发现您将td
样式设置为&#39; red&#39;或者&#39; blue&#39;但是我没有看到这些风格的宣言。
您也有语法错误 - 在shift键实现e.targetsetAttribute
上而不是e.target.setAttribute
正如DFord所说,将<script src = "draw.js">
更新为<script type="text/javascript">
。
function createCanvas() {
var side = 100;
var tbody = document.getElementById("tablebody");
for (var i = 0; i < side; ++i) {
var row = document.createElement("tr");
for (var j = 0; j < side; ++j) {
var cell = document.createElement("td");
row.appendChild(cell);
}
tbody.appendChild(row);
}
document.getElementById("canvas").addEventListener(
"mousemove", processMouseMove, false);
}
function processMouseMove(e) {
if (e.target.tagName.toLowerCase() == "td") {
if (e.ctrlKey) {
e.target.setAttribute("class", "blue");
}
if (e.shiftKey) {
e.target.setAttribute("class", "red");
}
}
}
window.addEventListener("load", createCanvas, false);
function erase() {
var tb = document.getElementsByTagName('table');
var tbc = tb[0].getElementsByTagName('td');
for (k = 0; k < tbc.length; k++) {
tbc[k].style.backgroundColor = 'pink'
}
}
&#13;
table {
width: 400px;
border-collapse: collapse;
}
td {
width: 4px;
height: 4px;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Erase Drawing Window</title>
<body>
<table id="canvas">
<caption>Hold <em>Ctrl</em> (or <em>Control</em>) to draw blue. Hold <em>Shift</em> to draw red.</caption>
<tbody id="tablebody"></tbody>
</table>
</body>
&#13;
这应该现在可以使用