【问题标题】:Click to scroll inside an overflowed horizontal div单击以在溢出的水平 div 内滚动
【发布时间】:2016-12-20 19:16:02
【问题描述】:

我正在使用以下代码在页面中构建图像轮播。我添加了一些 JS 代码,以便在单击它们时能够滚动到特定图像,但它没有按我预期的那样工作。也就是说,当我单击图像时,我希望 div 滚动到该特定图像。

有什么想法吗?任何帮助将不胜感激。

谢谢!

HTML:

<div class="carousel-frame">
    <ul>
        <li class="carousel-item">
            <img width="600" height="400" src="img01.jpg" />
        </li>
        <li class="carousel-item">
            <img width="600" height="400" src="img02.jpg" />
        </li>
        <li class="carousel-item">
            <img width="600" height="400" src="img03.jpg" />
        </li>
        <li class="carousel-item">
            <img width="600" height="400" src="img04.jpg" />
        </li>
    </ul>
</div>

CSS:

.carousel-frame {
    width: 100%;
    margin-bottom: 2em;
    padding-bottom: 1em;
    overflow-x: scroll;
    white-space: nowrap;
}

.carousel-frame ul {
    margin: 0;
    padding: 0;
    height: 100%;
    list-style: none;
}

.carousel-frame li {
    display: inline-block;
    margin: 0 5px 0 0;
    padding: 0;
}

JS:

$('.carousel-frame .carousel-item').on('click', function(e) {
    var slideWidth = $(this).width();
    var scrollTo = $(this).position().left;
    var offset = scrollTo - (slideWidth / 2);
    $(this).parent().parent().animate({
        scrollLeft: offset
    }, 500);
    e.preventDefault();
});

小提琴:

https://jsfiddle.net/occrnja9/9/

【问题讨论】:

  • “它没有按我的需要工作”不能很好地描述您的问题。能否请您解释一下并显示哪些问题无法正常工作(图片可以提供帮助)。
  • 对不起。当我单击图像时,我需要 div 滚动到该特定图像。现在,当我单击一些图像时,div 会滚动回到开头。不确定我是否解释过自己。
  • 当您单击图像时,您希望 div 滚动到 CLICKED 图像吗?也就是你想让点击的图片在div的中心对齐?
  • 没错,我希望点击的图像在 div 的中心对齐。

标签: jquery html css scroll carousel


【解决方案1】:

我设法找到了解决方案。

JS:

$('.carousel-frame .carousel-item').on('click', function(e) {
    var container = $(this).parent().parent();
    var slideWidth = $(this).width();
    var frameWidth = container.width() / 2;
    var slidePosition = $(this).position().left;
    var offset = container.scrollLeft() + slidePosition - frameWidth + slideWidth / 2;
    container.animate({
        scrollLeft: offset
    }, 500);
    e.preventDefault();
});

小提琴:

https://jsfiddle.net/occrnja9/10/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多