滚动到div水平不工作

时间:2016-07-21 09:14:10

标签: jquery css scroll

我有以下代码。我试图在点击按钮时水平滚动到div。



jQuery(document).ready(function() {
  jQuery("#clickme").click(function() {

    jQuery("#parent").animate({
      scrollLeft: jQuery("#child").position().left
    }, 500);
  });
});

#parent {
  width: 1000px;
  height: 200px;
  background: #ccc;
  position: relative;
}
#child {
  position: absolute;
  right: 200px;
  height: 100px;
  width: 100px;
  background: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <button id="clickme">
    Click Me
  </button>
  <div id="child">
    child div
  </div>
</div>
&#13;
&#13;
&#13;

控制台中没有错误。我做错了什么?

2 个答案:

答案 0 :(得分:3)

&#34;你应该制作动画,因为它是有滚动条的人。&#34;

如果方案类似于this

,您的代码应该是正确的

(只需改变你的CSS)

#parent {
  width: 350px; /* Make it shorter for scroll to work */
  height: 200px;
  background: #ccc;
  position: relative;
  overflow: scroll; /* To show scrollbar */
}
#child {
  position: absolute;
  right: -150px; /* Make it negative also to make scroll working */
  height: 100px;
  width: 100px;
  background: blue;
}

正如你在那里看到的那样,如果你的代码就像那样......

但是现在,我将根据你当前的情况......

来自jQuery("#parent"),应为jQuery("body")

现在工作:

&#13;
&#13;
jQuery(document).ready(function() {
  jQuery("#clickme").click(function() {

    jQuery('body').animate({
      scrollLeft: jQuery("#child").position().left
    }, 500);
  });
});
&#13;
#parent {
  width: 1000px;
  height: 200px;
  background: #ccc;
  position: relative;
}
#child {
  position: absolute;
  right: 200px;
  height: 100px;
  width: 100px;
  background: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <button id="clickme">
    Click Me
  </button>
  <div id="child">
    child div
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

请看下面的代码。对于滚动动画,请转到jQuery("html,body").animation而不是#parent

jQuery(document).ready(function() {
  jQuery("#clickme").click(function() {

    jQuery("html,body").animate({
      scrollLeft: jQuery("#child").position().left
    }, 500);
  });
});
#parent {
  width: 1000px;
  height: 200px;
  background: #ccc;
  position: relative;
}
#child {
  position: absolute;
  right: 200px;
  height: 100px;
  width: 100px;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <button id="clickme">
    Click Me
  </button>
  <div id="child">
    child div
  </div>
</div>

相关问题