代码之家  ›  专栏  ›  技术社区  ›  Mona Coder

单击时无法将DIV滚动到页面顶部

  •  0
  • Mona Coder  · 技术社区  · 7 年前

    我正在做这个演示。为什么我不能动画 #box-2 单击时从上到下按DIV?

    $('#box-2').animate({scrollTop : 0},700);
    

    $("#box-2").on("click", function(){
     	$('#box-2').animate({scrollTop : 0},700);
    });
    body, html {
      width: 100%;
      height: 100%; }
    
    .box{
      height: 100vh;
    }
    #box-1{
    	background:khaki;
    }
    #box-2{
    	background:red;
    }
    #box-3{
    	background:green;
    }
    #box-4{
    	background:orange;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <div class="col-md-12 box" id="box-1" >	</div>
    <div class="col-md-12 box" id="box-2" >	</div>
    <div class="col-md-12 box" id="box-3" >	</div>
    <div class="col-md-12 box" id="box-4" >	</div>
    4 回复  |  直到 6 年前
        1
  •  1
  •   Sanjit Bhardwaj    7 年前

    fiddle code check this fiddle 检查这个小提琴

    您正在单击方框2,希望它不会位于顶部,但它已经位于顶部,正如您所看到的。

        2
  •  0
  •   kmoser    7 年前

    您需要指定 $('html,body') ,如本答案所述: https://stackoverflow.com/a/18780639/378779

        3
  •  0
  •   David Söderberg    7 年前

    $('.mybtn').click(function(){
       $('html,body').animate({
          scrollTop: $('.blue').offset().top
       },'slow');
    });
    .red{
       background-color:red;
       height:100vh;
       }
       
       .blue{
          background-color:blue;
          height:100vh;
       }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='red'>
      <button class='mybtn'>Click here to scroll to blue div</button>
    </div>
    <div class='blue'></div>
        4
  •  0
  •   kmoser    7 年前

    最初不清楚你的意思是什么:

    单击时将Box-2 DIV设置为顶部

    既然你已经要求 移动 #box-2 在屏幕顶部(我将解释为“物理上高于 #box-1 )我将向您介绍以下代码:

    $("#box-2").on("click", function(){
        $('#box-2:parent').each(function () {
            $(this).insertBefore($(this).prev('#box-1'));
        });
    });
    

    回答如下: Switch positions of 2 divs with jQuery