如何在jquery

时间:2016-12-16 17:45:23

标签: jquery

我陷入了困境  我希望当我在一个块中单击“添加”文本时,我的垂直滚动也会移动并聚焦在我单击的点上。
之前:
enter image description here

单击“添加”以克隆元素。添加了一个块,滚动不会改变。我的屏幕显示了克隆的块 enter image description here
我希望滚动更改为我跟踪我点击的项目如下:
enter image description here

我有一些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>

你有什么建议吗?

2 个答案:

答案 0 :(得分:0)

使用jquery animate函数

$('.like').click(function(){
    $(this).html("added");
    $(this).clone().appendTo('#add');

    $("html, body").animate({ scrollTop: $(document).height() }, 1000);

})

我添加的代码从上到下为滚动条设置动画

您需要从顶部获取新的div距离并将$(document).height()替换为它。

的示例:

Offset()

var height = $("div").offset().top();

$("html, body").animate({ scrollTop: height }, 1000);

答案 1 :(得分:0)

我发现答案如下:
更新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);
        }
    })

});