垂直对齐div但保持水平位置不变

stU*_*Urb 24 javascript php mysql jquery

从一个数据库中,我正在拉出一种具有某个起点和某个终点的Div的时间轴.它们中的一些重叠,其中一些可以彼此相邻. 来自数据库

最终我想将它们一起滑动,以便它尽可能紧凑,如下所示: 我们想要实现的目标

我怀疑如何应对这一挑战:通过服务器端(php)脚本或一些javascript浮动脚本thingy.或者当然是一种完全不同的方法

有人可以把我推向正确的方向吗?

编辑::重要的是,因为它是一个时间轴,div的水平位置保持不变.所以将所有div向左浮动或内联阻塞它们是没有选择的:)

我的数据库设置:

id | name | start | end  
1  | a    | 2     | 7  
2  | b    | 5     | 10  
etc
Run Code Online (Sandbox Code Playgroud)

Sto*_*fke 13

<!DOCTYPE html>
<html>
<!--
  Created using jsbin.com
  Source can be edited via http://jsbin.com/udofoq/26/edit
-->
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css">div.blue {
    background-color: #a4dcdf;
}

div.orange {
    background-color: #fd9226;
}

div.green {
    background-color: #88b37e;
}

div.yellow {
    background-color: #d8d03f;
}

div.red {
    background-color: #c16558;
}
div.grey {
    background-color: #cdcdcd;
}
div.hours1{
  top: 0px;
  left: 10px;
  width: 100px;//(110-10)
}
div.hours2{
  top: 30px;
  left: 80px;
  width: 50px;
}
div.hours3{
  top: 60px;
  left: 120px;
  width: 50px;
}

div.hours4{
  top: 90px;
  left: 5px;
  width: 70px;
}

div.hours5{
  top: 120px;
  left: 110px;
  width: 30px;
}
div.hours6{
  top: 150px;
  left: 130px;
  width: 70px;
}
div.hours {
  position: absolute;
  height:20px;
  color: white;
  text-align:center;
  border:white;
  -webkit-box-shadow: 3px 3px 6px 2px rgba(00, 00, 00, .2);
  box-shadow: 3px 3px 6px 2px rgba(00, 00, 00, .2);
  font: bold 18px Arial, Helvetica, Geneva, sans-serif;
  line-height:20px;     
}

button{
    position:static;
    margin-top:200px;
}
.collapse,
.overlap1,
.overlap2,
.overlap3,
reset{
    float:left;
}
</style></head>
<body>
  <div class="hours hours1 orange">A</div>
<div class="hours hours2 yellow">B</div>
<div class="hours hours3 blue">C</div>
<div class="hours hours4 green">D</div>
<div class="hours hours5 red">E</div>
<div class="hours hours6 grey">F</div>
<button class="collapse">collapse</button>
<button class="overlap1">sort</button>
<button class="reset">reset</button>

<script>
data1 = [
  [1, 10, 110],
  [2, 80, 130],
  [3, 120, 170],
  [4, 5, 70],
  [5, 110, 140],
  [6, 130, 180]
];

//just added for console output not needed
var divider="";
for (var i = 0; i < 80; i++) {
  divider += "_";
}

console.log(divider);
console.log("ORIGINAL ARRAY DATA1:", data1);


//add a column to keep track of the row, to start set it to  row 1
data1 = $.each(data1, function(index, value) {
  value[3] = 0;
});

console.log(divider);
console.log("ORIGINAL dataA WITH ADDED COLUMN:", data1);

function timelinesort(dataA){

//make a new Array to store the elements in with their new row number
var dataB = dataA.slice(0, 1);

console.log(divider);
console.log("INITIALIZED dataB WITH FIRST ELEMENT FROM dataA:", dataB);


//initialize the counter
var counter = 0;

console.log(divider);
console.log("INITIALIZED ROUNDS COUNTER:", counter);


dataA = $.map(dataA, function(value1, index1) {

//increment counter with 1 
counter++;

console.log(divider);
console.log("INCREMENTED ROUNDS COUNTER:", counter);


  dataA = $.map(dataA, function(value2, index2) {


    //exclude comparing an element with itself
    if(value2 != dataB[0]) {
      //check to see if elements overlap
      if(value2[2] >= dataB[0][1] && value2[1] <= dataB[0][2]) {
        console.log(divider);
        console.log("Round " + counter  + " from dataA: [" + value2 + "] overlaps with " + dataB[0] + " incrementing row counter with 1");
        //increment the value in column 3 (row counter) of the array
        value2[3]++;
        console.log(divider);
        console.log("Now the dataA has changed to this:", dataA);
        console.log("Meanwhile data1 has changed to this:", data1);
      } else {
        //if no overlap occurs check if the element is not already in the dataB array and if not check if it doesn't overlap with the existing elements
        if($.inArray(value2, dataB) == -1) {
          $.each(dataB, function(index3, value3) {
            if(value3[2] >= value2[1] && value3[1] <= value2[2]) {
              console.log(divider);
              console.log("Round " + counter + " from dataA: [" + value2 + "] overlaps with " + value3 + " incrementing row counter with 1");
              dataB.pop();
              //increment the value in column 3 (row counter) of the array
              value2[3]++;
            } else {
              //if no overlap occurs add the value to dataB
              dataB.push(value2);
              console.log(divider);
              console.log("Added [" + value2 + "] to dataB and now dataB has changed to this: ", dataB);
            }
          });
        } else {
          dataB.push(value2);
          console.log("Added [" + value2 + "] to dataB and now dataB has changed to this: ", dataB);
        }
      }
    }
    return [value2];
  });
  dataA = jQuery.grep(dataA, function(item) {
    return jQuery.inArray(item, dataB) < 0;
  });
  if(dataA.length >= 1) {
    dataB.unshift(dataA[0]);
    dataB = dataB.splice(0, 1);
  } else {
    dataA = [];
  }

});

}
//run the function
timelinesort(data1);

console.log(divider);
console.log("Finally the data1 has changed to this:", data1);


$(".collapse").click(function() {
  $.each(data1, function(index, value) {
    $("div.hours" + (index + 1)).animate({
      "top": 0
    }, "slow");
  });

});

$(".overlap1").click(function() {
  $.each(data1, function(index, value) {
    console.log("div.hours" + (index + 1) + ":" + (value[3]) * 26);
    $("div.hours" + (index + 1)).animate({
      "top": (value[3]) * 26
    }, "slow");
  });

});

$(".reset").click(function() {
  $.each(data1, function(index, value) {
    $("div.hours" + (index + 1)).removeAttr('style');
  });

});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我所做的是将所有行折叠到第一行,然后检查哪些行与该行的原始重叠,如果是这样,在重叠的行上增加行号,然后转到下一行并重复该过程直到所有元素都整齐堆叠.

你仍然需要清理javascript/jquery的东西并把它放在一个很好的函数中.但作为概念的证据似乎有效

工作实例:


http://jsbin.com/udofoq/26/watch

要么

http://jsfiddle.net/stofke/7VP5U/


Mic*_*kij 5

看看我的小提琴.我认为它可以用你想要的数量来完成.块数据取自HTML表.

JS:

var data = [],
    rows = [],
    chart = $('.wrapper-inner');


function DataItem(id, name, start, end){
     this.id = id;
     this.name = name;
     this.start = start;
     this.end = end;
}

$('.data tr').each(function() {
    var $this = $(this),
        item = new DataItem( $this.find('td:eq(0)').text(),
                             $this.find('td:eq(1)').text(),
                             $this.find('td:eq(2)').text(),
                             $this.find('td:eq(3)').text() );
        data.push(item);
});

function addRow(){
    var row = {
        el : $('<div class="row"></div>').appendTo(chart),
        positions: []
    };

    rows.push( row );
}

function checkRow(rowId, item){        
    var isRowAvailible = true;

    for (var i = 0; i < +item.end - +item.start; i++){
        if (rows[rowId].positions[+item.start + i]){
            isRowAvailible = false;
            break;
        }
    }

    return isRowAvailible;
}

function markRowPositions(rowId, item){


    for (var i = 0; i < item.end - item.start; i++){
        rows[rowId].positions[+item.start + i] = true;
    }

}

function addItems(){
    for (var i = 0; i < data.length; i++){
        (function(i){
            setTimeout(function() {addItem(data[i])}, 100 * i);
        })(i)
    }
}

function addItem(item){
    var rowToAdd = false,
        itemEl = $('<div class="item"></div>');

    for (var i = 0; i < rows.length; i++){
        if ( checkRow(i, item) ){
            rowToAdd = i;
            break;    
        }
    }

    if (rowToAdd === false){
        addRow();
        rowToAdd = rows.length - 1;
    }

    rows[ rowToAdd ].el.append(itemEl);

        console.log(itemEl.css('opacity'))

    itemEl.css({
        'left': item.start * 30,
        'opacity' : 1,
        'width': ( ( item.end - item.start ) * 30 ) - 2
    });


    markRowPositions(rowToAdd, item);



}

addItems();
Run Code Online (Sandbox Code Playgroud)

  • 你投入的工作量是+1 (2认同)

UV.*_*UV. 2

您的问题听起来很天真,但如果需要以最优化的方式解决,它实际上包含一些复杂的元素。

我可能会做些什么来生成你的显示的快速答案 -

  1. 使用提供的函数将行号添加到表中
  2. 使用 PHP 代码为每行生成一个带有 style="display:block" 的 DIV 容器

  3. 在行内生成适当大小的 DIV (结束开始 * 比例),样式 =“display:inline-block; float:left; display:relative” 并(编辑:)添加透明 DIV 元素以补偿您需要的空白。(即从0到开始以及从结束到下一个DIV的开始)

  4. 在 DIV 元素内添加名称字段

use mySchema; drop procedure if exists tileItems;

DELIMITER $$
CREATE PROCEDURE tileItems ()
BEGIN
DECLARE p_id, p_start, p_end, p_row int;
DECLARE done INT DEFAULT FALSE;
DECLARE cur1 CURSOR FOR SELECT id, start, end FROM tasks order by start, id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

drop temporary table if exists tiles;

create temporary table tiles (
row int(11) NOT NULL,
id int(11) NOT NULL,
end int(11) NOT NULL
);
-- row field will indicates the row number the task should apear
OPEN cur1;
next_task: LOOP

FETCH cur1 into p_id, p_start, p_end;
  IF (done) THEN
    LEAVE next_task;
  END IF;
select min(row) from (select row, max(end) me from tiles t2 group by row) t1 
  where me < p_start
  into p_row;


-- take care of row numbering  
IF (p_row IS NULL) then
  select max(row) from tiles
    into p_row;
    IF (p_row IS NULL) then
      SET p_row = 0;
    END IF;
    SET p_row=p_row+1;
END IF;

insert into tiles (id, row, end)
  values (p_id,p_row,p_end);

END LOOP;

-- CLOSE cur1;
-- here is your output, on the PHP/.Net code you should loop on the row 
select tasks.*, tiles.row from tasks
inner join tiles
 on tasks.id = tiles.id
order by tiles.row, tasks.start;


END $$
DELIMITER ;   
Run Code Online (Sandbox Code Playgroud)

这是我用来检查的表格 -

CREATE TABLE `tasks` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `start` int(11) NOT NULL,
  `end` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;


INSERT INTO `tasks` (`id`, `name`, `start`, `end`) VALUES
(1, 'A', 2, 6),
(2, 'B', 5, 7),
(3, 'C', 8, 10),
(4, 'D', 1, 5),
(5, 'E', 6, 7);
Run Code Online (Sandbox Code Playgroud)

关于优化的几句话(我最喜欢的主题之一:) - 在此代码中没有优化,这意味着任务将分配到第一个可用行。为了最大限度地减少行数,可以(但需要一些时间)创建一个使用启发式方法来解决此问题的函数。

输出:

id  name    start   end row
4   D   1   5   1
5   E   6   7   1
3   C   8   10  1
1   A   2   6   2
2   B   5   7   3
Run Code Online (Sandbox Code Playgroud)