gpt4 book ai didi

jquery - 水平滚动到 div 不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:46 25 4
gpt4 key购买 nike

我有以下代码。我试图通过单击按钮水平滚动到一个 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>

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

最佳答案

“你应该为它设置动画,因为它有滚动条。”

如果场景类似于 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")

现在工作:

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

jQuery('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>

关于jquery - 水平滚动到 div 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38499911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com