jquery 计数元素并显示/更新视图中的当前值+总计

p4tfgftt  于 2023-10-17  发布在  jQuery
关注(0)|答案(2)|浏览(120)

我试图了解如何计算和显示当前和总数字在我的网页上。
我的html

<div class="is-vertical">
<figure><img src="src.jpg"><figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption></figure>
<figure><img src="src.jpg"><figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption></figure>
<figure><img src="src.jpg"><figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption></figure>
</div>

我的js试图得到总数

var totalItems = $( ".is-vertical figure" ).length;

我的js尝试在追加的span中显示变量

$('.is-vertical').append('<span class="numbers">')+totalItems.join('</span>');
    
});

对于显示当前图形的最后一部分,我想知道是否可以使用($(window).scrollTop()以某种方式更新视图中当前图形的值。

sqougxex

sqougxex1#

要构造一个jQuery元素,你需要以下结构:

$('<span>', { class: 'numbers', text: figureCount });

或者:

$('<span>').addClass('numbers').text(figureCount);

工作示例

const $isVertical = $('.is-vertical'); // <div class="is-vertical">
const figureCount = $isVertical.find('figure').length; // 3

$isVertical.append($('<span>', { class: 'numbers', text: figureCount }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="is-vertical">
  <figure><img src="src.jpg">
    <figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption>
  </figure>
  <figure><img src="src.jpg">
    <figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption>
  </figure>
  <figure><img src="src.jpg">
    <figcaption class="wp-element-caption">Towers Day<br>NYC</figcaption>
  </figure>
</div>
raogr8fs

raogr8fs2#

它最终被这个脚本解决了:

var $isVertical = $('.is-vertical'); // <div class="is-vertical">
var $numbersSpan = $('<span>', { class: 'numbers', text: 'Figure 1 of ' + $isVertical.find('figure').length });
$isVertical.prepend($numbersSpan);

// Function to update the current figure number
function updateCurrentFigureNumber() {
  var windowHeight = $(window).height();
  var scrollTop = $isVertical.scrollTop();
  var figureHeight = $isVertical.find('figure').height();
  
  // Calculate the current figure number in view
  var currentFigureNumber = Math.floor((scrollTop + windowHeight * 0.75) / figureHeight) + 1;
  
  // Update the text inside the 'numbers' span
  $numbersSpan.text( + currentFigureNumber + ' / ' + $isVertical.find('figure').length);
}

// Add an event listener to update the current figure number when scrolling
$isVertical.scroll(updateCurrentFigureNumber);

// Call the updateCurrentFigureNumber function initially to set the correct figure number
updateCurrentFigureNumber();

相关问题