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

问题描述 投票:1回答:3

我正在尝试制作一个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;
}
javascript image html-table
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;
}

1
投票

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

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

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


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'的值,如果有,请告诉用户单击其他地方)并提示其转向它是。

© www.soinside.com 2019 - 2024. All rights reserved.