dongshao8125
dongshao8125
2014-01-21 06:36

将图像或css样式图标放置在单击的(网格)单元格内

This is my code to create table with php by looping. I add an onclick function in each . So that on clicking a particular cell the background color is changed. Now i want to place a particular image..inside each cell that is being clicked..but am not able to figure out that function.

I want to write a function such that an image is placed when clicked.

/* 
 * javascript function that changes color of the cell.
 * 
*/

 <script>
    function changeColor(elem)
    {     
    elem.style.background = "red";     
    }
 </script>

Table created in php

<?php
    $rows = 10; // define number of rows
    $cols = 4;// define number of columns

    echo "<table border='1'>";

    for($tr=1;$tr<=$rows;$tr++){

        echo "<tr>";
            for($td=1;$td<=$cols;$td++){
                   echo "<td onclick=\"changeColor(this)\" > ".$tr." ".$td."</td>";
            }
        echo "</tr>";
    }

        echo "</table>";
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongqian5639 dongqian5639 7年前

    Use this:

    elem.innerHTML = '<img src="path/to/image.png" />';
    
    点赞 评论 复制链接分享
  • doujiu3768 doujiu3768 7年前

    JS

    elem.style.backgroundImage ="url('"+imageUrl +"')";
    

    Jquery

    $('elem').css('background-image', 'url(' + imageUrl + ')');
    
    点赞 评论 复制链接分享
  • douzhan1994 douzhan1994 7年前

    Replace

      elem.style.background = "red";     
    

    with this for javascript

      elem.style.backgroundImage ="url('path/myimage.jpg')";
    

    use this for jQuery

      $(elem).css('background-image', "url('path/myimage.jpg')");
    

    FOR DRAWING A CIRCLE TRY THIS (ADD THIS POINT TO THE ORIGINAL QUESTION AS WELL)

    You might want to have a look at HTML5 CANVAS

    You will have to add a canvas tag in the td and send its reference to the function

        var offsets = elem.getBoundingClientRect();
        var top_C = offsets.top;
        var left_C = offsets.left;
        var bottom_C= offsets.bottom;
        var right_C= offsets.right;
        var y_C= ((bottom_C-top_C)/2); // Y- Co=ordinates
        var x_C=((right_C-left_C)/2);  // X- Co=ordinates
        var ctx=elem.getContext("2d");
        ctx.beginPath();
        ctx.arc(x_C,y_C,40,0,2*Math.PI);
        ctx.stroke();
    

    You might have to do try it a couple of times to get the perfect radius that fits your cell. The third argument in ctx.arc()

    点赞 评论 复制链接分享