仅强制三列布局JS Jquery

时间:2018-09-20 12:32:54

标签: javascript jquery

页: https://ntsu.unioncloudsandpit.org/resources

DOM中的每一行结果都类似

<div class="uc-document-row">
    <div class="uc-document-block ">
        <div class="uc-doc-bg-ext">
            <a class="uc-doc-bg-ext-wrapper" title="2013 Exec Elections Results" href="/resources/2013-exec-elections-results"></a>
            <div class="clear"></div>
        </div>
        <div class="uc-document-titles">
            <h2>2013 Exec Elections Results</h2>
            <h3>application-vnd-openxmlformats-officedocument-wordprocessingml-document</h3>
        </div>
        <span class="uc-doc-upload-time">
            17 September 2018
        </span>
        <div class="uc-resource-summary">
            <p></p>
        </div>
        <div class="uc-resource-show-download">
            <a title="Details" class="uc-resource-details-link btn-2018" href="/resources/2013-exec-elections-results" style="font-size: 10px;">Details</a>
            <a class="uc-resource-download-link btn-2018" href="https://ntsu.unioncloudsandpit.org/resources/2013-exec-elections-results/download_attachment" style="font-size: 10px;">Download</a>
        </div>
        <div class="clear"></div>
    </div>

每行4个。

要输入三列布局,我可以删除第四列并重新排序,例如:

$('.uc-document-row .uc-document-block:nth-child(4)').remove();
$('.uc-document-block').css('width','21%');
$('.uc-document-block').css('padding','4%');
$('.uc-document-block').css('margin','2');

但是,我该如何实际重新排序,以便第四个元素向下移动到下一行并确保每行恰好有3个项目? 我认为这需要detach / prependTo吗?

我只能通过JavaScript与页面交互。

1 个答案:

答案 0 :(得分:0)

检查以下javascript代码:

$('.uc-document-list > .uc-document-row').each(function(){
    var currentBlocksCount = $(this).find('.uc-document-block ').length;
    // console.log('currentBlocksCount=', currentBlocksCount);
    var flagNextBlock = false;
    if( $(this).next('div').hasClass('uc-document-row') ) {
        flagNextBlock = true;
    }
    // console.log('flagNextBlock=', flagNextBlock);
    if( !flagNextBlock ) {
        $(this).after('<div class="uc-document-row"></div>');
    }
    var nextBlockObj = $(this).next('div.uc-document-row');
    if( currentBlocksCount > 3 ) {
        $(this).find('.uc-document-block').each(function(key, value){
            if( key > 2 ) {
                var cloneObj = $(this).clone();
                nextBlockObj.append(cloneObj);
                $(this).remove();
            }
        });
    }
});