[英]how to keep scroll position to focus the element after add element in jquery
I was stuck in the situation. 我陷入了困境。
I hope that when I click "add" text in a block, my vertical scroll also move and focus on the point I clicked. 我希望当我单击一个块中的“添加”文本时,我的垂直滚动条也会移动并集中在单击的点上。
Before: 之前:
After I click add to clone the element. 单击添加后,克隆元素。 A block was added and the scroll does not change. 添加了一个块,并且滚动不会更改。 My screen show the block which was cloned 我的屏幕显示了被克隆的块
I expect that the scroll change to I trace the item I clicked as bellow: 我希望滚动更改为跟踪下面单击的项目:
I have some jquery code as bellow: 我有一些jquery代码,如下所示:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.like').click(function(){
$(this).html("added");
$(this).clone().appendTo('#add');
})
});
</script>
<body>
<div style="width: 1000px; height: 200px; background: white;"></div>
<div>--------------------------------------</div>
<div id="add"></div>
<div>--------------------------------------</div>
<div class="container">
<div style="width: 100px; height: 400px; background: red;" class="like" id ="0"><span>add</span></div>
<div style="width: 100px; height: 400px; background: blue;" class="like" id ="1"><span >add</span></div>
<div style="width: 100px; height: 400px; background: yellow;" class="like" id ="2"><span >add</span></div>
<div style="width: 100px; height: 400px; background: red;" class="like" id ="3"><span >add</span></div>
</div>
</body>
Do you have any suggestion? 你有什么建议吗?
use jquery animate function 使用jQuery动画功能
$('.like').click(function(){
$(this).html("added");
$(this).clone().appendTo('#add');
$("html, body").animate({ scrollTop: $(document).height() }, 1000);
})
The code that I added animates the scroll bar from the top to bottom 我添加的代码使滚动条从上到下动画化
You need to get your new div distance from the top and replace $(document).height()
with it. 您需要从顶部获得新的div距离,并用它替换$(document).height()
。
examples: 例子:
var height = $("div").offset().top();
$("html, body").animate({ scrollTop: height }, 1000);
I found out the answer as bellow: 我发现答案如下:
Update JS: 更新JS:
$(document).ready(function() {
$('.like').click(function() {
var x = $(this).offset().top;
var xx = $(this).position().top-$(window).scrollTop();
alert($(window).height() +'---' + $(document).height());
var id = $(this).attr('id');
if ($(this).html() == 'add') {
$(this).html("added");
$(this).clone().appen dTo('#add');
$("html, body").animate({
scrollTop : xx + $(this).height()
}, 3000);
} else {
$(this).html("add");
var a = $(this).attr('id');
$('#add').find('#' + id).remove();
$("html, body").animate({
scrollTop : xx - $(this).height()
}, 3000);
}
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.