容器内的水平滚动

我是javascript的新手,我正在尝试创建一个水平滚动div: –

的jsfiddle

你可以看到菜单链接转到每种颜色,但我想把它放在一个250x250px的容器中,所以只有1种颜色可见,然后你点击任何一个链接,它滚动到那种颜色。

希望有人可以帮助我一些指示。

谢谢!

jQuery(document).ready(function ($) { $(".scroll").click(function (event) { event.preventDefault(); $('html,body').animate({ scrollLeft: $(this.hash).offset().left }, 200); }); }); 
 .container { white-space: nowrap; } .child-element { min-width: 250px; display: inline-block; height: 250px; } .child1 { background-color: purple; } .child2 { background-color: orange; } .child3 { background-color: black; } .child4 { background-color: green; } .child5 { background-color: blue; } .child6 { background-color: red; } 
  PURPLE ORANGE BLACK GREEN BLUE RED 

正如@ Script47所提到的,你需要将overflow-x作为CSS属性应用于你的元素,另外还有width (用作视口)。 这是你的最终CSS可能是什么样子:

 .container { white-space: nowrap; overflow-x: scroll; width: 250px; position: relative; } 

之后,您需要稍微修改您的JS。 您仍然希望滚动到元素的offset ,但您还需要考虑当前的scroll位置。

(澄清一下,如果你点击orange – 最初的偏移量为250px ,动画后,橙色的偏移量为0pxblack250px 。如果你再点击black ,它将尝试滚动到250px ,是橙色元素。)

这是更新的JS可能的样子:

 jQuery(document).ready(function ($) { $(".scroll").click(function (event) { var current = $('.container').scrollLeft(); var left = $(this.hash).position().left; event.preventDefault(); $('.container').animate({ scrollLeft: current + left }, 200); }); }); 

一个小提琴演示: https : //jsfiddle.net/bpxkdb86/4/

对于小提琴,我使用删除了HTML中的物理white-space (以防止div之间有空格),并且还添加了position: relative对于包含元素(使用position

一个CSS解决方案,尝试将此添加到CSS中的元素,

 overflow-x: scroll; 

这个,应该为你做。

您需要进行两项更改才能生效。

首先,为容器添加高度和宽度,然后在css中设置溢出。

 width:250px; height:250px; overflow: auto; 

第二次更新jquery来为容器设置动画,现在它正在为主体设置动画。

 $('.single-box').animate({ 

JSFiddle在以下链接中是可用的

https://jsfiddle.net/jym7q0Lu/

如果你想让你的div可以滚动,只需使用一个CSS。

  .container { white-space: nowrap; overflow-x: scroll; width: 250px; position: relative; }