简体   繁体   中英

Place an image or a css style icon inside the cell (of the grid) that is clicked

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>";
?>

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()

用这个:

elem.innerHTML = '<img src="path/to/image.png" />';

JS

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

Jquery

$('elem').css('background-image', 'url(' + imageUrl + ')');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM