【问题标题】:Center the focused item in horizontal scroll在水平滚动中居中焦点项目
【发布时间】:2019-08-25 20:55:50
【问题描述】:

我用<HTML/>CSS 创建了一个水平滚动容器:

body {
background-color: #212121;
}

.scroll_container {
	height: 100px;
	width: 400px;
	display: flex;
	align-items: center;
	overflow-y: hidden;
	width: 100%;
	height: 20%;
}

.scroll_container_sub {
	height: 100px;
	min-width: 230px;
	float: none;
	display: inline-block;
	zoom: 1;
	margin: 10px;
	border: solid 1px transparent;
	border-radius: 15px;
	background-color: #fff;
}
<div class="scroll_container">
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
</div>

我尝试什么:
是否有可能每次一项(scroll_container_sub)都以scroll_container 为中心?尤其是移动使用,这个非常好。
示例:
滚动后,中间项目水平居中:

(图片:移动视图)
这意味着这样的事情不应该存在:

因为没有一个容器是居中的。当我查看这样的滚动位置时,滚动视图应该将其中一个容器居中。
希望获得更多详细信息::)
在以下链接中,您会看到我尝试实现的目标。只看开头的几秒钟。
每次用户刷卡后,卡片都会居中。正是我试图实现的目标:
https://www.youtube.com/watch?v=UsXv6VRqZKs 你需要一个活生生的例子吗?没问题。在 Google Play 商店中,您可以找到它们。例如这个刷卡器:

~菲利普

【问题讨论】:

  • 你的意思是让元素最初居中显示(因此中间的项目将水平位于屏幕的中心),还是让它们填满屏幕宽度,或者其他什么?
  • @YellowAfterlife 我提供了一个例子。你能看看我的编辑吗?

标签: javascript html css uiscrollview uislider


【解决方案1】:

一般公式如下 - 你找到你感兴趣的元素,找到它的中点 (x + width / 2),然后从中减去容器宽度的一半:

window.addEventListener("load", function(e) {
  var container = document.querySelector(".scroll_container");
  var middle = container.children[Math.floor((container.children.length - 1) / 2)];
  container.scrollLeft = middle.offsetLeft +
    middle.offsetWidth / 2 - container.offsetWidth / 2;
});
body {
background-color: #212121;
}

.scroll_container {
	height: 100px;
	width: 400px;
	display: flex;
	align-items: center;
	overflow-y: hidden;
	position: relative;
	width: 100%;
	height: 20%;
}

.scroll_container_sub {
	height: 100px;
	min-width: 230px;
	float: none;
	display: inline-block;
	zoom: 1;
	margin: 10px;
	border: solid 1px transparent;
	border-radius: 15px;
	background-color: #fff;
}
<div class="scroll_container">
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
        <div class="scroll_container_sub"></div>
</div>

如果您想动态应用此效果,您可能希望等到用户完成滚动,计算新的滚动目标,并随着时间的推移逐渐趋近。

编辑:对于纯 CSS 解决方案,请参阅 scroll-margin(在撰写本文时,尚未普遍支持)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多