两个事件监听器之后只有第一个工作JavaScript

时间:2016-12-22 19:57:07

标签: javascript events event-listener

我正在创建一个绘图应用程序。每次点击我的画布时,我都会在画布上画一个带背景色的div。由于我也想在点击和拖动时进行绘制,因此我创建了一个布尔值,以查看用户是否在执行mousemove事件侦听器中的代码之前单击了它。当我在我的changeCanvas函数中放置一个事件监听器,但是当我将mousedown和mouseover放在changeCanvas函数中时,第二个不起作用。 这是代码,我的HTML只包含两个div。一个托盘div和一个canvas div。谢谢!

var selectedColour = 0;
var paint = false;
var colours = ["red", "yellow", "green", "black", "gray"];

function createPallet(){
    for (var i = 0; i < colours.length; i++){
        var colour = document.createElement("div");
        colour.classList.add("colour");
        var pallet = document.getElementById('pallet');
        pallet.style.width="100px";
        pallet.style.height="300px";
        var canvas = document.getElementById("canvas");
        canvas.style.width="500px";
        canvas.style.height="300px";
        colour.style.backgroundColor = colours[i];
        colour.id = colours[i];
        pallet.appendChild(colour);
        colour.addEventListener("click", pickCol);
    }   
}

function pickCol(e){
    selectedColour = e.target.id;

    console.log(selectedColour);
}

function changeCanvas(){
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", mouseDown);
    canvas.addEventListener("mousemove", paint);
}
function mouseDown(){
    paint=true;
}

function paint(e){
    if(paint){
        var newDiv = document.createElement("div");
        newDiv.classList.add("newDiv"); 
        newDiv.style.backgroundColor = selectedColour;
        canvas.appendChild(newDiv);
        console.log(e.pageX);
        console.log(e.pageY);
        newDiv.style.width= "5px";
        newDiv.style.height= "5px";
        newDiv.style.top = e.pageY + "px";
        newDiv.style.left = e.pageX + "px";
        newDiv.style.position="absolute";
    }
}

createPallet();
changeCanvas();

0 个答案:

没有答案