1

我正在尝试制作井字游戏。我使用的是图像而不是 Xs 和 Os,因此在单击 td 时需要用图像填充它。我试过这个:

function makeDuck(place){
    //this is just so I know the other methods work
    alert("duck");            
    //This is the line I need help with 
    window.location.write('<img src="smallDuck.jpg" width="70" height="70"/>'); 
    squares[place] = 1;
}

function makeBeaver(place){
    //this is just so I know the other methods work
    alert("beaver"); 
    //This is the line I need help with           
    document.zero.write('<img src="smallBeaver.jpg" width="80" height="80"/>');
    squares[place] = 2;
}
4

3 回答 3

2
function makeDuck(place){
    // first, we must create a new element in the DOM
    var img = document.createElement("IMG");
    // second, we must assign the right attributes
    img.src = "smallDuck.jpg";
    img.width = "70";
    img.height = "70";

    // finally, we append it to the document
    document.body.appendChild(img);

    squares[place] = 1;
}

function makeBeaver(place){
    // first, we must create a new element in the DOM
    var img = document.createElement("IMG");
    // second, we must assign the right attributes
    img.src = "smallBeaver.jpg";
    img.width = "80";
    img.height = "80";

    // finally, we append it to the document
    document.body.appendChild(img);

    squares[place] = 2;
}
于 2012-06-29T00:23:36.333 回答
1

一种方法是使用 javascript 替换IMG. 所以假设你有一个 3 x 3 的网格,每个单元格都包含一个<img />标签。他们都需要 unique ids。

您将拥有 3 张图片:blank.jpg、X.jpg 和 Y.jpg。所有单元格都以
<img src='blank.jpg' ... />

使用 Javascript 定位元素 (getDocumentById(id)) 并将其属性设置为设置为X 或 Y 图像src的 URI 。src

于 2012-06-29T00:49:18.683 回答
0

以下应该让你开始,首先是样式:

<style type="text/css">
table.game {
  border: none;
  border-collapse: collapse;
}
table.game td {
  height: 50px;
  width: 50px;
  margin: 0;
  padding: 0;
}
td.topLeft, td.topCenter, td.midLeft, td.midCenter {
  border-right: 1px solid black;
  border-bottom: 1px solid black;
}

td.topRight, td.midRight {
  border-bottom: 1px solid black;
}

td.botLeft, td.botCenter {
  border-right: 1px solid black;
}

td.botRight { }

.naught {
  background-image: url('naught.jpg');
}
.cross {
  background-image: url('cross.png');
}

</style>

然后是游戏的 HTML

<table class="game" onclick="handleClick(event);">
  <tr>
    <td class="topLeft">
    <td class="topCenter">
    <td class="topRight">
  <tr>
    <td class="midLeft">
    <td class="midCenter">
    <td class="midRight">
  <tr>
    <td class="botLeft">
    <td class="botCenter">
    <td class="botRight">
</table>

然后是一个交换图像的简单脚本:

<script>
var handleClick = (function() {
    var count = 0;

    return function(evt) {
      var el = evt.target || evt.srcElement;
      el.className += ' ' + (count++%2? 'naught' : 'cross');
    }
}());
</script>

请注意,您应该处理对同一个单元格的多次点击(检查该类是否已经具有“naught”或“cross”的值,如果有,请告诉用户单击其他地方)并给出轮到它的提示是。

于 2012-06-29T02:16:27.397 回答