programing

3디브마다 디브로 포장합니다.

css3 2023. 10. 2. 15:20

3디브마다 디브로 포장합니다.

사용가능한가요?nth-child3 div를 랩핑할 셀렉터 사용.wrapAll? 나는 정확한 방정식을 구할 수 없을 것 같습니다.

그래서...

<div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
</div>

...이 됩니다.

<div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
</div>

다음과 같이 사용할 수 있습니다.

var divs = $("div > div");
for(var i = 0; i < divs.length; i+=3) {
  divs.slice(i, i+3).wrapAll("<div class='new'></div>");
}

여기서 데모를 해보실 수 있습니다. 여기서 하는 일은 랩하고 싶은 요소를 가져와 반복해서 3개씩 묶음으로 작업한 다음 다음 3개로 이동하는 것뿐입니다.한 번에 3개씩 포장이 되고 마지막에 3개, 3개, 3개, 2개가 남습니다.

이것을 꽤 쉽게 할 수 있는 일반 청크 함수를 작성했습니다.

$.fn.chunk = function(size) {
    var arr = [];
    for (var i = 0; i < this.length; i += size) {
        arr.push(this.slice(i, i + size));
    }
    return this.pushStack(arr, "chunk", size);
}

$("div > div").chunk(3).wrap('<div class="new"></div>');

$.fn.chunk = function(size) {
  var arr = [];
  for (var i = 0; i < this.length; i += size) {
    arr.push(this.slice(i, i + size));
  }
  return this.pushStack(arr, "chunk", size);
}

$("div > div").chunk(3).wrap('<div class="new"></div>');
div > div {
  width: 50px;
  height: 50px;
  background: blue;
  margin: 2px;
  float: left;
}

div.new {
  background: red;
  height: auto;
  width: auto;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
</div>

플러그인

$(function() {
    $.fn.EveryWhat = function(arg1) {
        var arr = [];
        if($.isNumeric(arg1)) {
            $.each(this, function(idx, item) {
                var newNum = idx + 1;
                if(newNum%arg1 == 0)
                arr.push(item);
            });
        }
        return this.pushStack(arr, "EveryWhat", "");
    }
});

사용법.

불러EveryWhat()요소에 숫자를 입력하고 수집하고자 하는 모든 요소에 대한 숫자를 입력합니다.

$("div").EveryWhat(2).wrapInner('<div class="new" />');

wrapinner의 따옴표는 형식이 적절해야 합니다.<div class="new" />클래스와 클로징 태그를 달았습니다.스택 오버플로는 그것이 어떻게 생겼는지 보여줄 수 없지만 여기 셀프 클로징 디브의 링크가 있습니다.

어떤 모습이어야 하는지에 대해서.

지정한 다른 번호는 모두 포장됩니다.jquery 1.8.2를 사용하고 있으므로 셀렉터 호출을 사용하는 것을 기억하십시오.EveryWhat(3)시간대별로 번호를 매길 수 있습니다.물론 그것을 페이지 하단에 넣거나 포장합니다.

$(document).ready(function() {  
    //place above code here
});

모든 n을 사용할 수 있고 그 다음에.wrapInner('<div class="new" />')동일한 결과에 대하여

다음은 위의 Nick의 더 사용 가능한 버전입니다.

window.WrapMatch = function(sel, count, className){
  for(var i = 0; i < sel.length; i+=count) {
    sel.slice(i, i+count).wrapAll('<div class="'+className+'" />');
  }
}

다음과 같이 사용할 수 있습니다.

var ele = $('#menu > ul > li'); 
window.WrapMatch(ele, 5, 'new-class-name');

물론 창은 핸들러 네임스페이스로 대체되어야 합니다.

업데이트됨:jQuery를 활용하는 약간 더 나은 버전

(function($){
  $.fn.wrapMatch = function(count, className) {
    var length = this.length;
    for(var i = 0; i < length ; i+=count) {
      this.slice(i, i+count).wrapAll('<div '+((typeof className == 'string')?'class="'+className+'"':'')+'/>');
    }
    return this;
  }; 
})(jQuery);

다음과 같이 사용:

$('.list-parent li').wrapMatch(5,'newclass');

래퍼 이름의 두 번째 매개 변수는 선택 사항입니다.

$(function() {
    $.fn.WrapThis = function(arg1, arg2) { /*=Takes 2 arguments, arg1 is how many elements to wrap together, arg2 is the element to wrap*/

        var wrapClass = "column"; //=Set class name for wrapping element

        var itemLength = $(this).find(arg2).length; //=Get the total length of elements
        var remainder = itemLength%arg1; //=Calculate the remainder for the last array
        var lastArray = itemLength - remainder; //=Calculate where the last array should begin

        var arr = [];

        if($.isNumeric(arg1))
        {
            $(this).find(arg2).each(function(idx, item) {
                var newNum = idx + 1;

                if(newNum%arg1 !== 0 && newNum <= lastArray){
                    arr.push(item);
                }
                else if(newNum%arg1 == 0 && newNum <= lastArray) {
                    arr.push(item);
                    var column = $(this).pushStack(arr);
                    column.wrapAll('<div class="' + wrapClass + '"/>'); //=If the array reaches arg1 setting then wrap the array in a column
                    arr = [];
                }
                else if(newNum > lastArray && newNum !== itemLength){ //=If newNum is greater than the lastArray setting then start new array of elements
                    arr.push(item);
                }
                else { //=If newNum is greater than the length of all the elements then wrap the remainder of elements in a column
                    arr.push(item);
                    var column = $(this).pushStack(arr);
                    column.wrapAll('<div class="' + wrapClass + '"/>');
                    arr = []
                }
            });
        }
    }
});

카일의 플러그인 아이디어를 받아 자동으로 랩하고 두 가지 주장을 하도록 확장했습니다.처음에는 효과가 없었지만 몇 가지 편집과 코드 추가를 통해 실행에 옮겼습니다.

함수를 호출하려면 랩할 내용의 상위 요소를 사용한 다음 인수를 다음과 같이 설정합니다.

$('#container').WrapThis(5, 'li');

첫 번째 인수는 몇 개의 요소를 함께 래핑할 것인지이고 두 번째 인수는 래핑할 요소 유형입니다.

변수 아래 주함수에서 래핑 요소의 클래스를 변경할 수 있습니다.wrapClass.

저는 이 문제와 중복되는 또 다른 문제를 위해 이 답을 준비했습니다.그래서 어쩌면 내 변종이 누군가에게 유용할지도 모릅니다.

세 가지 요소를 모두 포장할 수 있는 솔루션은 다음과 같습니다.

var $lines = $('.w-col'), // All Dom elelements with class .w-col
     holder = []; //Collect DOM elelements

$lines.each(function (i, item) {
  holder.push(item);

  if (holder.length === 3) {
    $(holder).wrapAll('<div class="w-row" />');
    holder.length  = 0;
  }
});

$(holder).wrapAll('<div class="w-row" />'); //Wrap last elements with div(class=w-row)

저는 jsbin에서 http://jsbin.com/necozu/17/ 또는 http://jsbin.com/necozu/16/ 에서 몇 가지 개선된 코드를 작성했습니다.

언급URL : https://stackoverflow.com/questions/3366529/wrap-every-3-divs-in-a-div