簡體   English   中英

javascript / jquery選擇行中的最后一個元素

[英]javascript/jquery selecting last element in row

我正在使用“ float:left”將塊放置在容器中。 在大屏幕上像這樣:

在此處輸入圖片說明

在小屏幕上:

在此處輸入圖片說明

用戶單擊任何元素時,我可以選擇行中的最后一個元素嗎?

如果元素都是內聯或浮動的,則不會有"last element on row"的概念。

我建議您使用已知值來計算元素:

$('.box').on('click', function (e) {
  // calculate how many boxes will be in a "row" 
  var windowWidth = $('ul').width();
  var boxWidth = $('.box').outerWidth();
  var boxesPerRow = ~~(windowWidth / boxWidth);

  // get the index of the clicked element
  var index = $(e.currentTarget).index();
  // get the column of the clicked element
  var col = (index % boxesPerRow) + 1;
  // calculate how far it is to the end of this row, 
  // and select that element
  var $endOfRow = $('.box').eq(index + boxesPerRow - col);
  if (!$endOfRow.length) $endOfRow = $('.box').last();

});

用有效的方法更新了我的答案。 這是小提琴: http : //jsfiddle.net/gvbw9Lkz/4/

另外,您可以通過比較它們的position()值來動態計算出哪些元素在同一行中:

 $(function() { // cache the collection of all the blocks var blocks = $('.block'); blocks.on('click', function() { blocks.removeClass('highlight'); var $this = $(this); // get the y coordinate of the clicked block var y = $this.position().top; // store the blocks in the row var rowBlocks = $this; // search backwards until we find a different y coordinate or reach 0 for (var i = $this.index() - 1; i >= 0; i--) { var block = blocks.eq(i); if (block.position().top == y) { // add the element to the rowBlocks selector rowBlocks = rowBlocks.add(block); } else { // different coordinate, stop searching break; } } // search forwards until we find a different y coordinate or reach the end for (var i = $this.index() + 1; i < blocks.length; i++) { var block = blocks.eq(i); if (block.position().top == y) { // add the element to the rowBlocks selector rowBlocks = rowBlocks.add(block); } else { // different coordinate, stop searching break; } } // hightlight the row rowBlocks.addClass('highlight'); }); }); 
 .container { width: 300px; } .block { background-color: #000; width: 50px; height: 50px; margin: 10px; float: left; } .block.highlight { background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="container"> <div class="block">1</div> <div class="block">2</div> <div class="block">3</div> <div class="block">4</div> <div class="block">5</div> <div class="block">6</div> <div class="block">7</div> <div class="block">8</div> <div class="block">9</div> <div class="block">10</div> <div class="block">11</div> <div class="block">12</div> <div class="block">13</div> <div class="block">14</div> <div class="block">15</div> <div class="block">16</div> <div class="block">17</div> <div class="block">18</div> <div class="block">19</div> <div class="block">20</div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM