javascript - html中的水平滑动

标签 javascript jquery html css

我知道这是一个常见问题,但我找不到符合我要求的答案。

简而言之,我想从屏幕的右侧(不可见)部分向左水平滑动一个框,然后再从左侧向右滑动。

下面的 html/css/js 演示了我想要的:

<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<style type="text/css">
#box-1 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 80em;
  background-color: #f00;
}
#box-2 {
  position: absolute;
  top: 0;
  right: -100%;
  width: 100%;
  height: 4em;
  background-color: #0f0;
}
#viewport {
  overflow: hidden;
  position: relative;
  height: 100em;
}
#container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
</style>
</head>
<body>
<div id="viewport">
  <div id="container">
    <div style="position: relative">
      <div id="box-1">
      </div>
      <div id="box-2">
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
$("#box-1").click(function () {
    $(this).parent().parent().animate({left: "-100%"});
});
$("#box-2").click(function () {
    $(this).parent().parent().animate({left: "0"});
});
</script>
</body>
</html>

现在,除了两件重要的事情外,一切似乎都很好:

  • 我不想为外部视口(viewport)指定高度。我希望此视口(viewport)自动采用容器中最高元素的高度
  • 如果您在看到红色框时在页面底部向下滚动并单击它,则此代码不会执行我想要的操作:绿色框出现在视口(viewport)内,但它在底部滚动。我希望绿色框直接进入视野。作为奖励,如果一旦绿色框出现在 View 中,如果我单击它,红色框会回到其先前滚动位置的 View 中,那就太好了。

当然,这个例子还有很多其他的限制(jquery 提供的默认动画功能很烂,等等),但我相信我可以稍后修复它们。

考虑到我在此处发布的解决方案的局限性,我怀疑我没有选择正确的方法,但我不知道应该从哪里开始。

最佳答案

单击框时需要滚动到 div 的顶部。 这是代码:

$(function() {
    var vheight = Math.max($("#box-1").height(), $("#box-2").height());
    $("#viewport").height(vheight)
});
$("#box-1").click(function () {
    $(this).parent().parent().animate({left: "-100%"});
    $('html,body').animate({
       scrollTop: $("#box-1").offset().top
    });
});
$("#box-2").click(function () {
    $(this).parent().parent().animate({left: "0"});
    $('html,body').animate({
       scrollTop: $("#box-2").offset().top
    });
});

我还更新了 JS Fiddle:http://jsfiddle.net/Av7P3/1/

关于javascript - html中的水平滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927684/

相关文章:

javascript - 如何选择字符串中接下来的两个字符?

javascript - 显示 :target popup on page load With PURE CSS

javascript - 将 json 存储为变量以便在另一个函数中重用

html - 有哪些好的解决方法可以解决 Mozilla Firefox 中的 "Visiblility: Collapse"错误?

JavaScript/jQuery : Detect when each individual image loads

javascript - 如何使用 jquery/javascript 格式化时间

javascript - Tumblr:删除阅读更多链接

javascript - 使用 Tabulator 设置最大表格高度

java - AJAX/Spring MVC - 没有 Spring Security 的 403 禁止错误

html - div 在 css 图像之前没有覆盖在 div 中