繁体   English   中英

将“绘制表格”功能-从jQuery转换为纯JS

[英]converting “drawing in a table” functionality - from jQuery to pure JS

我在css-tricks网站上的表格中找到了易于绘制的示例。 使用jQuery,它看起来像这样:

$("#drawing-table").delegate("td", "mousedown", function() {
        mouseDownState = true;
        $el = $(this);
        if (eraseState) {
            $el.removeAttr("style");
        } else {
            $el.css("background", curColor);
        }
    }).delegate("td", "mouseenter", function() {
        if (mouseDownState) {
            $el = $(this);
            if (eraseState) {
                $el.removeAttr("style");
            } else {

                // DRAWING ACTION
                $el.css("background", curColor);
            }
        }
    });
    $("html").bind("mouseup", function() {
        mouseDownState = false;
    });

但是我需要使用jQuery的方法。 因此,我尝试将其转换为纯JS。 但是现在我没有按预期工作。 这是我得到的:

theTable = document.getElementById("drawing-table");

theTable.addEventListener("mousedown", function(e) {
    if (e.target.tagName === 'TD') {
        mouseDownState = true;
        el = e.target;
        if (eraseState) {
            el.removeAttribute("style");
        }
        else {
            el.style.backgroundColor = curColor;
        }
    }
});

theTable.addEventListener("mouseenter", function(e) {
    if (e.target.tagName === 'TD') {
        if (mouseDownState) {
            el = e.target;

            if (eraseState) {
                 el.removeAttribute("style");
            }
            else {
                el.style.backgroundColor = curColor;
            }
        }
    }
});

document.addEventListener("mouseup", function() {
    mouseDownState = false;
});

当我按住鼠标左键并将光标移到要着色的单元格上时,脚本应更改单元格的颜色(例如在Paint中)。 但这只会为我单击的单元格上色。 我认为问题是因为在jQuery版本中, mouseenter事件侦听器在mousedown事件侦听器之后立即运行。 但是我不知道如何将一个事件监听器放在另一个事件监听器上。

原始代码来自https://css-tricks.com/examples/DrawingTable/

您只需在代码中使用“ onmouseover”而不是“ mouseenter”侦听器即可。

theTable.onmouseover = function(e){
        if (e.target.tagName === 'TD') {
            if (mouseDownState) {
                el = e.target;

                if (eraseState) {
                    el.removeAttribute("style");
                }
                else {
                    el.style.backgroundColor = curColor;
                }
            }
        }
    }

看起来您只是在鼠标进入时才触发事件。 每当鼠标进入表格单元格时,jQuery代码就会触发。 当鼠标进入元素时,Mouseenter事件仅触发一次。 当您在元素上移动鼠标时,它不会反复触发。 尝试将处理程序附加到表中的所有单元格

暂无
暂无

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

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