我正在尝试使用Javascript来显示图像

时间:2012-06-29 00:05:32

标签: javascript image html-table

我正在尝试制作一个tic tac toe游戏。我正在使用图像而不是X和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;
}

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

这样做的一种方法是使用javascript替换IMG的来源。假设您有一个3 x 3网格,每个单元格包含一个<img />标记。他们都需要独特的id s。

你将有3张图片:blank.jpg,X.jpg和Y.jpg。所有细胞都以
开始 <img src='blank.jpg' ... />

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

答案 2 :(得分: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'的值,如果是,请告诉用户单击其他位置)并给出提示轮到了。