2016-12-16 13 views
1

私はこの状況に悩まされていました。
ブロック内の「追加」テキストをクリックすると、垂直スクロールも移動し、クリックしたポイントにフォーカスすることを願っています。前

enter image description herejqueryで要素を追加した後にスクロール位置を保持して要素をフォーカスする方法

私は要素のクローンを作成するために追加]をクリックした後。ブロックが追加され、スクロールは変更されません。

<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> 
:私は怒鳴るなど、いくつかのjqueryのコードを持って
enter image description here

を:私の画面は、私は私に、スクロールの変化は、私はのように怒鳴るクリックしたアイテムをトレースすることを期待し
enter image description here
をクローン化したブロックを示し、

ご意見はありますか?

答えて

0

使用jqueryのアニメーション機能

$('.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); 
+0

「私は新しいのdiv意志知らないが私はあなたに高さを伝えることはできませんので、追加してください。 あなたはそれを見ることができます -

新しい要素が領域に追加されます。私はあなたの提案を実行しようとしましたが、動作しません。 (コンテナ#3).offset()。トップ()。( – user3205761

+0

Maby '$(" html、body "))アニメーション({scrollTop:$("コンテナ).offset() }、1000); ' – Tonza

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); 
     } 
    }) 

}); 
関連する問題