简体   繁体   English

Javascript和jQuery中图像上的可点击网格

[英]Clickable grid over image in Javascript and jQuery

I have an image (1000x1300 pixel) and want to overlay it with a grid with 10x10 pixel cells (so this would be 100x130 cells). 我有一张图片(1000x1300像素),并希望将其与具有10x10像素单元的网格重叠(因此这将是100x130单元)。 Then there must be a way to click left mouse button, move over the grid an "mark" the underlying grid cells (ie change background color). 然后必须有一种方法可以单击鼠标左键,在网格上方移动“标记”基础网格单元(即更改背景颜色)。 At the time I have the following source code in jQuery 当时我在jQuery中有以下源代码

$(window).ready(function() {
    $("body").mousedown(function() { mstate = 1; }).mouseup(function() { 
        mstate = 0; 
    });
    var container = document.getElementById("grid");
    var divs = "";
    for (var y in grid) {
        divs += "<tr>";
        for (var x in grid[y]) {
            var class = "cellinactive";
            if (grid[y][x]==1) class = "cellactive";
            else if (grid[y][x]==2) class = "cellreserved";
            else if (grid[y][x]==3) class = "cellsold";
            divs += "<td class='" + class + "'>&nbsp;</td>";
        }
        divs += "</tr>";
    }
    divs = "<table>" + divs + "</table>";
    container.innerHTML = divs;
    $("#grid td").css({ "opacity": "0.7" }).html("").mouseover(function() {
        if (mstate == 1) {
            if (rgb2hex($(this).css("background-color")) == "#ffff00") 
                $(this).css("background-color", "#0ff");
            else 
                $(this).css("background-color", "#ff0");
        }
    });
});

var grid = "";
var mstate = 0;

grid contains an 2-dimensional array (size is 130x100). 网格包含二维数组(大小为130x100)。 I tried to create a grid basing on DIVs, but that's much slower than TDs. 我试图基于DIV创建一个网格,但这比TD慢得多。 Has anyone some hint to gain performance of this snippet? 有没有人暗示要提高此代码段的性能? When testing in Firefox 4, that "click, hold down and moving" of mouse is not much performant, there are gaps when drawing continously a line. 在Firefox 4中进行测试时,鼠标的“单击,按住和移动”效果不佳,连续画线时会有空隙。 (Sorry when my english is not the best ;) Regards (对不起,当我的英语不是最好的时候;)

You might find it easier to use DOM techniques rather than creating a string: 您可能会发现使用DOM技术比创建字符串更容易:

Live Demo 现场演示

(Just a basic version, supports clicks but not drags) (仅是基本版本,支持单击但不支持拖动)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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