簡體   English   中英

禁用點擊事件監聽器

[英]Disable click EventListener

我正在嘗試學習HTML5畫布。 第一張圖片需要點擊七下,然后出現貓吃餅干的gif圖像。 最初,我將單擊EventListener綁定到圖像。 出現吃餅干的貓gif后,我無法禁用該點擊。 有什么建議么?

cat.html

<!DOCTYPE html>
<html>
    <head>
        <title>Cat Animation</title>
    </head>
    <body>
        <div id="canvasDiv"></div>
        <script type="text/javascript" src="cat.js"></script>
        <script type="text/javascript">
            prepareCanvas(document.getElementById("canvasDiv"), 700, 700);
            document.getElementById("canvas").addEventListener("click", function(){console.log("clicked");loadImage("cat");console.log(total);console.log(currentFrame);}, false);
        </script>
    </body>
</html>

cat.js

var canvas;
var context;
var image;
var currentFrame = 0;
var frames = 4;
var width = 350;
var height = 300;
var total = 0
var finalFrame = 0;

function prepareCanvas(canvasDiv, canvasWidth, canvasHeight)
{
    canvas = document.createElement('canvas');
    canvas.setAttribute('width', canvasWidth);
    canvas.setAttribute('height', canvasHeight);
    canvas.setAttribute('id', 'canvas');
    canvasDiv.appendChild(canvas);

    context = canvas.getContext("2d");
    canvas.width = canvas.width;//clears canvas
    loadImage("cat");
};

function loadImage(name)
{
    image = new Image();
    image.src = "images/cat" + currentFrame +".png";
        draw("one");
    if (currentFrame == 3 && total == 1){
        setInterval(finaldraw,110);
    }
};

function draw(params)
{
    image.onload = function(){
        canvas.width = canvas.width;
        context.drawImage(image,0,0);
        currentFrame++;
        if (currentFrame == 4) {
            currentFrame = 0;
            total++;
        };
    }
};

function finaldraw(){
    document.getElementById("canvas").removeEventListener("click",function(){});
    image.src = "images/eatsheet.png";
    image.onload = function(){
        context.drawImage(image,350*finalFrame,0,width,350,0,0,width,350);
        if (finalFrame == frames) {
            finalFrame = 0;
        } else {
            finalFrame = finalFrame + 1;            
        }
    }
};

您需要刪除添加偵聽器時使用的完全相同的功能對象實例。 一個函數表達式求值到一個新的函數對象,即使它具有完全相同的內容(在您的情況下不是...),它也與原始注冊的對象不匹配。

解決方案是擁有一個命名函數或一個為其分配了函數值的變量,並在add和remove調用中使用相同的標識符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM