瓷砖并不总是第一次点击

时间:2011-11-17 16:52:01

标签: javascript jquery onclick

我有一个带可选择瓷砖的等轴测图。瓦片在单击时变为“突出显示”,并在单击其他瓦片时恢复正常。这是通过将背景图像更改为突出显示的图块之一来完成的。

但是,我注意到瓷砖并不总是能够识别出它们在第一次点击时被点击了。例如,首次启动时,单击最靠近屏幕的图块通常不会执行任何操作。再次点击它甚至三次将最终使其改变颜色,但是当尝试不同的图块时仍然存在这种多次点击要求。最终,一次点击后瓷砖会发生变化,或者如果在释放之前在瓷砖上按住鼠标按下一秒钟,则会发生变化。

在下面的示例中,您可以看到我的平铺点击事件处理程序。只需在JS代码中搜索“TODO”即可。 问题可能是因为有两个平铺点击事件。这个问题能解决吗?

http://jsfiddle.net/briz/jdhPW/8/

我建议你测试点击第一排瓷砖。瓷砖周围有透明像素,因此当您的鼠标仍然在其周围注册瓷砖时,很容易认为您正在点击中间的瓷砖。您可以看到哪个图块当前处于“活动状态”,因为它在悬停时变得略微透明。

编辑我找到了解决方案!我可以通过这样调用它来预先注册瓷砖:

$.fn.gameMap.tileInfo = function(tile,x,y) 
    {
        // Registers each tile with their unique id
        tile.id = obj.attr('id') + '_tile_' + x + '_' + y;

        // When the tile gets clicked
        tile.click(function() 
        {
                        .....
        }

然后,只有一个click事件实例,每次第一次点击时都可以使用

1 个答案:

答案 0 :(得分:1)

我使用比原版更多的jQuery来清理代码。

$.fn.gameMap.tileInfo = function(tile,x,y) {
    // When the tile gets clicked
    tile.click(function() {
        // When the tile gets clicked again?
        var regularTile = "url(http://i244.photobucket.com/albums/gg10/brizthewhitedragon/WorkTilesWatermark.png)";
        $(".content .tile").css("background-image", regularTile);
        // Makes the tile apparently selected
        var selectedTile = "url(http://i244.photobucket.com/albums/gg10/brizthewhitedragon/WorkTilesSelected.png)";
        tile.css("background-image", selectedTile);
    });
};

更好的方法是简单地将一个点击事件添加到这样的图块中,因为它会立即将它们全部绑定(尽管您需要稍微重新构建一下代码......):

var tiles = $(".content .tile").click(function() {
    // When the tile gets clicked again?
    var regularTile = "url(http://i244.photobucket.com/albums/gg10/brizthewhitedragon/WorkTilesWatermark.png)";
    tiles.css("background-image", regularTile);
    // Makes the tile apparently selected
    var selectedTile = "url(http://i244.photobucket.com/albums/gg10/brizthewhitedragon/WorkTilesSelected.png)";
    tile.css("background-image", selectedTile);
});