简体   繁体   English

jQuery水平滚动,项目宽度未知

[英]jQuery Horizontal scroll with unknown width of items

I am creating a gallery using jQuery which displays pictures horizontally, with a "left" and "right" button below, that scrolls the row of images. 我正在使用jQuery创建一个画廊,该画廊水平显示图片,下面带有“左”和“右”按钮,用于滚动图像行。 There are plenty of tutorials and plugins for this. 有很多的教程和插件。

The problem for me though, is that 1) I don't know the width of the images. 但是对我来说,问题是1)我不知道图像的宽度。 And 2) I need the item I scroll to, to be centered. 2)我需要将滚动到的项目居中。

How do I go about this? 我该怎么办?

Thanks a lot, Gorm 非常感谢Gorm


Okay, I will try to clarify. 好吧,我会尽力澄清。

Say I have a horizontal row of images (with fixed height but unknown width - though smaller than the surrounding container), with a 'next' and 'prev' button as 假设我有一排水平图像(高度固定但宽度未知-尽管小于周围的容器),并带有“下一个”和“上一个”按钮

<div class="imgContainer">
  <ul>
    <li><img src="01.jpg" alt=""></li>
    <li><img src="02.jpg" alt=""></li>
    <li><img src="03.jpg" alt=""></li>
    <li><img src="04.jpg" alt=""></li>
    ...
  </ul>
</div>
<a href="#" id="prev">Previous image</a>
<a href="#" id="next">Next image</a>

When the page loads, the first image is displayed at the center, with the next images going out to the right. 页面加载时,第一张图像显示在中间,第二张图像显示在右侧。

When you click on "Next image", the row of images will scroll to center the next image. 当您单击“下一幅图像”时,图像行将滚动到下一幅图像的中心。

I tried different "solutions", but I am too much a js/jquery rookie for this I think. 我尝试了不同的“解决方案”,但是我认为我是一个js / jquery新手。 So any help would be greatly appreciated. 因此,任何帮助将不胜感激。 :-) :-)

Well, 好,

  1. Calculate the width of the images 计算图像的宽度
  2. Center the item you're scrolling 居中滚动项目

Seriously though, you need to provide a bit more info to get meaningful answers. 认真地说,您需要提供更多信息才能获得有意义的答案。

You can calculate the width of images inside a collection like this: 您可以像这样计算集合内图像的宽度:

var totalWidth = 0;
$('.container img').each(function() {
    totalWidth += $(this).outerWidth();
});

Otherwise it's just simple arithmetics. 否则,这只是简单的算法。 Give some more details about the problems you're facing if this doesn't help. 如果这无济于事,请提供更多有关您面临的问题的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM