如何添加Div的行/列

时间:2022-08-27 18:17:09

Code is here: http://jsfiddle.net/jaredasch1/6dhc240q/5/

代码在这里:http://jsfiddle.net/jaredasch1/6dhc240q/5/

I know I've asked this question before, but I wasn't able to get a working answer for that. I'm working on a game where it starts out a 4 by 4 grid, and when you click on one of the divs, it toggles the color of the divs above, below, and next two the one being clicked on. This part is working perfectly fine, and when they are all the other color, they switch back to the original color. However, what I'm trying to do now has presented more of a challenge. Once they are all the second color, I want to add another column and row and reset them back to the original color.

我知道我以前曾问过这个问题,但我无法得到一个有效的答案。我正在开发一个以4乘4格开始的游戏,当你点击其中一个div时,它会切换上方,下方和接下来两个div的颜色。这部分工作得很好,当它们都是其他颜色时,它们会切换回原来的颜色。但是,我现在要做的就是提出更多的挑战。一旦它们都是第二种颜色,我想添加另一列和行并将它们重置为原始颜色。

This is where I have run into some trouble. For some reason, the grid isn't recreated. This is where you guys come in. I need hep writing a function or edits to my original script to make this happen. I have this all on a JSFiddle here

这是我遇到麻烦的地方。出于某种原因,不会重新创建网格。这是你们进来的地方。我需要写一个函数或编辑我的原始脚本来实现这一点。我在这里有一个JSFiddle

I'll also post all of the code here.

我还会在这里发布所有代码。

<!DOCTYPE html>
<body>
    <div id="button" class="on hover"></div>
<br>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
<br>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
<br>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
<br>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
    <div class="block hover"></div>
</body>

The CSS

CSS

.block {
    height:100px;
    width:100px;
    border-radius:10px;
    display:inline-block;
    background-color:#33CCFF;
}
#button {
    height:100px;
    width:410px;
    border-radius:10px;
    display:inline-block;
    background-color:#FF6666;
    margin-bottom:10px;
}
.on {
    background-color:#D633FF;
}

The JavaScript/jQuery

JavaScript / jQuery

var main = function () {
    var checkAll = function () {
        var allDivs = $("div.block");
        var classedDivs = $("div.block.on");

        var allDivsHaveClass = (allDivs.length === classedDivs.length);

        if (allDivsHaveClass) {
            allDivs.removeClass("on");
        }
    };
    $("div").mouseenter(function () {
        $(this).fadeTo("slow", 0.25);
        $(this).css('cursor', 'pointer');
    });
    $("div").mouseleave(function () {
        $(this).fadeTo("slow", 1);
        $(this).css('cursor', 'default');
    });
    $(".block").click(function () {
        $(this).toggleClass("on");
        $(this).prev().toggleClass("on");
        $(this).nextAll().eq(4).toggleClass("on");
        $(this).next().toggleClass("on");
        $(this).prevAll().eq(4).toggleClass("on");
        checkAll();
    });
    $("#button").click(function () {
        $(".block").removeClass("on");
    });
    $(document).keydown(function (key) {
        if (event.which === 32) {
            $(".block").removeClass("on");
        }
    });
};

$(document).ready(main);

Any help is welcome!

欢迎任何帮助!

3 个解决方案

#1


3  

While I think both your HTML and you JavaScript can use a lot more improvements, here's the bare minimum to get this working:

虽然我认为您的HTML和JavaScript都可以使用更多的改进,但这是实现这一目标的最低要求:

First of all, because the amount of blocks per row (and the amount of rows) is going to change, you can't use your hardcoded .eq(4) filter anymore. You will need to track a variable with that number and add 1 to it for every new level.

首先,因为每行的块数(以及行数)将会发生变化,所以不能再使用硬编码的.eq(4)过滤器了。您需要跟踪具有该数字的变量,并为每个新级别添加1。

var blocksPerRow = 4;

Replace all hardcoded .eq(4) to .eq(blocksPerRow) now.

现在将所有硬编码的.eq(4)替换为.eq(blocksPerRow)。

Whenever you want to add a new block to each row you will have to find a <br> element and add a new block after it. You can simply create a new block by cloning a random one (I chose the first one). Do use the true argument when cloning to also copy the events bound to it:

每当您想要为每一行添加新块时,您必须找到一个
元素并在其后添加一个新块。你可以通过克隆一个随机的块来创建一个新的块(我选择了第一个)。克隆时使用true参数还要复制绑定到它的事件:

var newBlock = $('.block:first');
$('br').after( newBlock.clone(true) ); 

You also want to add an entire row, so you could either use the variable from before and add that many blocks, or just grab the last br plus all the items that follow and clone those. Append them after the last block.

您还想添加整行,因此您可以使用之前的变量并添加许多块,或者只抓取最后一个br以及后面的所有项目并克隆它们。在最后一个块之后追加它们。

var newRow = $('br:last').nextAll().andSelf();
$('.block:last').after( newRow.clone(true) );

Now is the time to also update your variable

现在是时候更新变量了

blocksPerRow++;

Last thing to do is fix the styling. You use inline blocks and rely on the spaces between the elements to create whitespace. That breaks when you clone the last row, but it's better to rely on actual margins for spacing anyway. This did the trick:

最后要做的是修复样式。您使用内联块并依赖元素之间的空间来创建空格。克隆最后一行时会中断,但最好还是依靠实际的间距来进行间距。这样就可以了:

.block {
    float: left;
    display: block;
    margin: 3px;
}
br {
    clear: both;
}

Here you see a working example: jsFiddle

在这里你看到一个工作的例子:jsFiddle

As you can see I added a "cheat" button so you can quickly check for yourself that it works.

正如您所看到的,我添加了一个“作弊”按钮,以便您可以快速检查它是否有效。

#2


2  

First of all, nice concept...

首先,好概念......

Secondly, you have some issues, let's start with the basics so you can move on with your game:

其次,你有一些问题,让我们从基础开始,这样你就可以继续你的游戏了:

...it starts out a 4 by 4 grid...

......它从一个4乘4格开始......

have you ever ear the expression, if your code looks like copy/paste, you're doing it wrong? well, let's start with a grid:

如果你的代码看起来像复制/粘贴,你做错了吗?好吧,让我们从网格开始:

your code to start is:

你要开始的代码是:

<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>
<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>
<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>
<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>

how about if you do this dynamic?

如果你做这个动态怎么样?

function buildGrid(elm, rows, columns){
    for(iRow = 0; iRow < rows; iRow++)
    {
        elm.append("<br>");
        for(iCol = 0; iCol < columns; iCol++)
        {
            elm.append('<div class="block hover"></div>');
        }
    }
}

and then just called:

然后刚刚调用:

buildGrid($("body"), 4, 4);

example: http://jsbin.com/tunun/1/edit?html,css,js,output

例如:http://jsbin.com/tunun/1/edit?html,css,js,output

you can easily added the grid size in a global variable as

您可以轻松地将网格大小添加到全局变量中

var globalRows = 4, globalColumns = 4;

$(function() {
  buildGrid($("body"), globalRows, globalColumns);
});

makes it easier to append rows/cols later on...

以后可以更容易地添加行/列...


I want to add another column and row...

我想添加另一列和行...

So, you want 2 things: add a new column/row and make all events work in the new add row/columns

因此,您需要两件事:添加新的列/行并使所有事件在新的添加行/列中工作

1 - from the example above, you can simply do:

1 - 从上面的例子中,你可以简单地做:

buildGrid($("body"), ++globalRows, ++globalColumns);

or more, manually:

或更多,手动:

globalRows++; // same as globalRows = globalRows + 1;
globalColumns++;  // same as globalColumns = globalColumns + 1;
buildGrid($("body"), globalRows, globalColumns);

2 - to make all evens work with the new dynamically added objects (html nodes) you need to change your javascript a bit, as when you do:

2 - 为了让所有的evens都能使用新的动态添加对象(html节点),你需要稍微改变你的javascript,就像你做的那样:

$("div").mouseenter(function () {
    $(this).fadeTo("slow", 0.25);
    $(this).css('cursor', 'pointer');
});

jQuery will attach that event to all EXISTING div's ... not the ones added after this code was executed, for that, jQuery has the method on and the code above would be written as:

jQuery会将该事件附加到所有EXISTING div ...而不是在执行此代码后添加的事件,为此,jQuery启用了方法,上面的代码将写为:

$("body").on("mouseenter", "div", function () {
    $(this).fadeTo("slow", 0.25);
    $(this).css('cursor', 'pointer');
});

I hope this helps you on your task

我希望这可以帮助你完成任务

#3


-1  

One of the flaws in your html is that you can't manage the placement of your blocks based on their position on the page alone. Grouping each row of blocks into an additional div helps with the placement. From there, you can use jQuery to both clone a group of blocks and append it to the body in addition to adding a block to each row. The code for resetting the click functions to the new rows and blocks may need work and your CSS for the main button may need to be adjusted for the new with but I will leave that to you.

HTML中的一个缺陷是,您无法根据页面在页面上的位置来管理块的位置。将每行块分组为一个额外的div有助于放置。从那里,您可以使用jQuery克隆一组块并将其附加到正文,除了向每行添加一个块。将点击功能重置为新行和块的代码可能需要工作,主按钮的CSS可能需要针对新按钮进行调整,但我会留给您。

HTML

HTML

http://jsfiddle.net/2069ox68/3/
<!DOCTYPE html>
<body>
    <div id="button" class="on hover"></div>
    <div class="grid">
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
    </div>
</body>

JS/JQuery

JS / JQuery的

var main = function () {
    var checkAll = function () {
        var allDivs = $("div.block");
        var classedDivs = $("div.block.on");

        var allDivsHaveClass = (allDivs.length === classedDivs.length);

        if (allDivsHaveClass) {
            $('div.row:first').clone(true, true).appendTo($('div.grid'));
            var allRows = $("div.row");
            $("div.block:first").clone(true, true).appendTo(allRows);
            var allDivs = $("div.block");
            allDivs.removeClass("on");

        }
    };

    $("div.block").mouseenter(function () {
        $(this).fadeTo("slow", 0.25);
        $(this).css('cursor', 'pointer');
    });
    $("div.block").mouseleave(function () {
        $(this).fadeTo("slow", 1);
        $(this).css('cursor', 'default');
    });
    $(".block").click(function () {
        $(this).toggleClass("on");
        $(this).prev().toggleClass("on");
        $(this).nextAll().eq(4).toggleClass("on");
        $(this).next().toggleClass("on");
        $(this).prevAll().eq(4).toggleClass("on");
        checkAll();
    });
    $("#button").click(function () {
        $(".block").removeClass("on");

    });
    $(document).keydown(function (key) {
        if (event.which === 32) {
            $(".block").removeClass("on");
        }
    });
};

$(document).ready(main);

CSS

CSS

.block {
    height:100px;
    width:100px;
    border-radius:10px;
    display:inline-block;
    background-color:#33CCFF;
}
#button {
    height:100px;
    width:410px;
    border-radius:10px;
    display:inline-block;
    background-color:#FF6666;
    margin-bottom:10px;
}
.on {
    background-color:#D633FF;
}

#1


3  

While I think both your HTML and you JavaScript can use a lot more improvements, here's the bare minimum to get this working:

虽然我认为您的HTML和JavaScript都可以使用更多的改进,但这是实现这一目标的最低要求:

First of all, because the amount of blocks per row (and the amount of rows) is going to change, you can't use your hardcoded .eq(4) filter anymore. You will need to track a variable with that number and add 1 to it for every new level.

首先,因为每行的块数(以及行数)将会发生变化,所以不能再使用硬编码的.eq(4)过滤器了。您需要跟踪具有该数字的变量,并为每个新级别添加1。

var blocksPerRow = 4;

Replace all hardcoded .eq(4) to .eq(blocksPerRow) now.

现在将所有硬编码的.eq(4)替换为.eq(blocksPerRow)。

Whenever you want to add a new block to each row you will have to find a <br> element and add a new block after it. You can simply create a new block by cloning a random one (I chose the first one). Do use the true argument when cloning to also copy the events bound to it:

每当您想要为每一行添加新块时,您必须找到一个
元素并在其后添加一个新块。你可以通过克隆一个随机的块来创建一个新的块(我选择了第一个)。克隆时使用true参数还要复制绑定到它的事件:

var newBlock = $('.block:first');
$('br').after( newBlock.clone(true) ); 

You also want to add an entire row, so you could either use the variable from before and add that many blocks, or just grab the last br plus all the items that follow and clone those. Append them after the last block.

您还想添加整行,因此您可以使用之前的变量并添加许多块,或者只抓取最后一个br以及后面的所有项目并克隆它们。在最后一个块之后追加它们。

var newRow = $('br:last').nextAll().andSelf();
$('.block:last').after( newRow.clone(true) );

Now is the time to also update your variable

现在是时候更新变量了

blocksPerRow++;

Last thing to do is fix the styling. You use inline blocks and rely on the spaces between the elements to create whitespace. That breaks when you clone the last row, but it's better to rely on actual margins for spacing anyway. This did the trick:

最后要做的是修复样式。您使用内联块并依赖元素之间的空间来创建空格。克隆最后一行时会中断,但最好还是依靠实际的间距来进行间距。这样就可以了:

.block {
    float: left;
    display: block;
    margin: 3px;
}
br {
    clear: both;
}

Here you see a working example: jsFiddle

在这里你看到一个工作的例子:jsFiddle

As you can see I added a "cheat" button so you can quickly check for yourself that it works.

正如您所看到的,我添加了一个“作弊”按钮,以便您可以快速检查它是否有效。

#2


2  

First of all, nice concept...

首先,好概念......

Secondly, you have some issues, let's start with the basics so you can move on with your game:

其次,你有一些问题,让我们从基础开始,这样你就可以继续你的游戏了:

...it starts out a 4 by 4 grid...

......它从一个4乘4格开始......

have you ever ear the expression, if your code looks like copy/paste, you're doing it wrong? well, let's start with a grid:

如果你的代码看起来像复制/粘贴,你做错了吗?好吧,让我们从网格开始:

your code to start is:

你要开始的代码是:

<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>
<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>
<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>
<br>
<div class="block hover"></div><div class="block hover"></div><div class="block hover"></div><div class="block hover"></div>

how about if you do this dynamic?

如果你做这个动态怎么样?

function buildGrid(elm, rows, columns){
    for(iRow = 0; iRow < rows; iRow++)
    {
        elm.append("<br>");
        for(iCol = 0; iCol < columns; iCol++)
        {
            elm.append('<div class="block hover"></div>');
        }
    }
}

and then just called:

然后刚刚调用:

buildGrid($("body"), 4, 4);

example: http://jsbin.com/tunun/1/edit?html,css,js,output

例如:http://jsbin.com/tunun/1/edit?html,css,js,output

you can easily added the grid size in a global variable as

您可以轻松地将网格大小添加到全局变量中

var globalRows = 4, globalColumns = 4;

$(function() {
  buildGrid($("body"), globalRows, globalColumns);
});

makes it easier to append rows/cols later on...

以后可以更容易地添加行/列...


I want to add another column and row...

我想添加另一列和行...

So, you want 2 things: add a new column/row and make all events work in the new add row/columns

因此,您需要两件事:添加新的列/行并使所有事件在新的添加行/列中工作

1 - from the example above, you can simply do:

1 - 从上面的例子中,你可以简单地做:

buildGrid($("body"), ++globalRows, ++globalColumns);

or more, manually:

或更多,手动:

globalRows++; // same as globalRows = globalRows + 1;
globalColumns++;  // same as globalColumns = globalColumns + 1;
buildGrid($("body"), globalRows, globalColumns);

2 - to make all evens work with the new dynamically added objects (html nodes) you need to change your javascript a bit, as when you do:

2 - 为了让所有的evens都能使用新的动态添加对象(html节点),你需要稍微改变你的javascript,就像你做的那样:

$("div").mouseenter(function () {
    $(this).fadeTo("slow", 0.25);
    $(this).css('cursor', 'pointer');
});

jQuery will attach that event to all EXISTING div's ... not the ones added after this code was executed, for that, jQuery has the method on and the code above would be written as:

jQuery会将该事件附加到所有EXISTING div ...而不是在执行此代码后添加的事件,为此,jQuery启用了方法,上面的代码将写为:

$("body").on("mouseenter", "div", function () {
    $(this).fadeTo("slow", 0.25);
    $(this).css('cursor', 'pointer');
});

I hope this helps you on your task

我希望这可以帮助你完成任务

#3


-1  

One of the flaws in your html is that you can't manage the placement of your blocks based on their position on the page alone. Grouping each row of blocks into an additional div helps with the placement. From there, you can use jQuery to both clone a group of blocks and append it to the body in addition to adding a block to each row. The code for resetting the click functions to the new rows and blocks may need work and your CSS for the main button may need to be adjusted for the new with but I will leave that to you.

HTML中的一个缺陷是,您无法根据页面在页面上的位置来管理块的位置。将每行块分组为一个额外的div有助于放置。从那里,您可以使用jQuery克隆一组块并将其附加到正文,除了向每行添加一个块。将点击功能重置为新行和块的代码可能需要工作,主按钮的CSS可能需要针对新按钮进行调整,但我会留给您。

HTML

HTML

http://jsfiddle.net/2069ox68/3/
<!DOCTYPE html>
<body>
    <div id="button" class="on hover"></div>
    <div class="grid">
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
        <div class="row">
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
            <div class="block hover"></div>
        </div>
    </div>
</body>

JS/JQuery

JS / JQuery的

var main = function () {
    var checkAll = function () {
        var allDivs = $("div.block");
        var classedDivs = $("div.block.on");

        var allDivsHaveClass = (allDivs.length === classedDivs.length);

        if (allDivsHaveClass) {
            $('div.row:first').clone(true, true).appendTo($('div.grid'));
            var allRows = $("div.row");
            $("div.block:first").clone(true, true).appendTo(allRows);
            var allDivs = $("div.block");
            allDivs.removeClass("on");

        }
    };

    $("div.block").mouseenter(function () {
        $(this).fadeTo("slow", 0.25);
        $(this).css('cursor', 'pointer');
    });
    $("div.block").mouseleave(function () {
        $(this).fadeTo("slow", 1);
        $(this).css('cursor', 'default');
    });
    $(".block").click(function () {
        $(this).toggleClass("on");
        $(this).prev().toggleClass("on");
        $(this).nextAll().eq(4).toggleClass("on");
        $(this).next().toggleClass("on");
        $(this).prevAll().eq(4).toggleClass("on");
        checkAll();
    });
    $("#button").click(function () {
        $(".block").removeClass("on");

    });
    $(document).keydown(function (key) {
        if (event.which === 32) {
            $(".block").removeClass("on");
        }
    });
};

$(document).ready(main);

CSS

CSS

.block {
    height:100px;
    width:100px;
    border-radius:10px;
    display:inline-block;
    background-color:#33CCFF;
}
#button {
    height:100px;
    width:410px;
    border-radius:10px;
    display:inline-block;
    background-color:#FF6666;
    margin-bottom:10px;
}
.on {
    background-color:#D633FF;
}