Кнопка перехода на верхнюю страницу после прокрутки вниз - PullRequest
0 голосов
/ 29 июня 2018

Я создал метод, который переходит в верхнюю часть страницы каждый раз, когда я нажимаю на него. Проблема в том, что я хочу, чтобы эта кнопка отображалась только в том случае, если вы уже прокрутили вниз, а не только по умолчанию. Как я могу это определить? Вот мой код:

показать / скрыть кнопку - не работает:

scrollFunction() {
    if (document.body.scrollTop > 5 || document.documentElement.scrollTop >5) {
        document.getElementById("myBtn").style.display =  "block";
    } else {
        document.getElementById("myBtn").style.display = "none";
    }
}

прокрутка вверх - работает:

topFunction() {
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; 
}

Спасибо.

Ответы [ 4 ]

0 голосов
/ 29 июня 2018

Я вижу, что другие ответы основаны на jQuery, но я предлагаю вам следовать "угловому пути". В Angular вы можете прослушивать событие scroll через (scroll)="handleScroll()" и получать текущее смещение сверху через Math.abs(this.scroller.nativeElement.getBoundingClientRect().top) (getBoundingClientRect().top возвращает отрицательные числа, поэтому мы можем получить абсолютные значения через Math.abs). Наконец вы должны получить что-то вроде этого:

HTML

<div class="wrapper" (scroll)="handleScroll()" #scrollWrapper>
  <div class="scroll" #scroller></div>
</div>
<button *ngIf="showButton" (click)="scrollToTop()">To top</button>

КОМПОНЕНТ

@ViewChild('scrollWrapper') private scrollWrapper: ElementRef;
@ViewChild('scroller') private scroller: ElementRef;

public showButton: boolean = false;

public handleScroll(): void {
  const offsetTop: number = Math.abs(this.scroller.nativeElement.getBoundingClientRect().top); 
  this.showButton = offsetTop > 5;
}

public scrollToTop(): void {
  this.scrollWrapper.nativeElement.scrollTop = 0;
}

А вот и рабочий STACKBLITZ .

0 голосов
/ 29 июня 2018

Я использую этот код, просто измените CSS в соответствии с вашими потребностями.

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 100) {
      $('#scroll').fadeIn();
    } else {
      $('#scroll').fadeOut();
    }
  });
  $('#scroll').click(function() {
    $("html, body").animate({
      scrollTop: 0
    }, 600);
    return false;
  });
});
#scroll {
  position: fixed;
  right: 10px;
  bottom: 10px;
  cursor: pointer;
  width: 50px;
  height: 50px;
  background-color: #3498db;
  text-indent: -9999px;
  display: none;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

#scroll span {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -8px;
  margin-top: -12px;
  height: 0;
  width: 0;
  border: 8px solid transparent;
  border-bottom-color: #ffffff
}

#scroll:hover {
  background-color: #e74c3c;
  opacity: 1;
  filter: "alpha(opacity=100)";
  -ms-filter: "alpha(opacity=100)";
}
<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>

  <!-- BackToTop Button -->
  <a href="javascript:void(0);" id="scroll" title="Scroll to Top" style="display: none;">Top<span> </span></a>

  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  
</body>
0 голосов
/ 29 июня 2018

Попробуйте следующий пример, чтобы сделать плавный переход:

$(document).scroll(function() {

  if ($(this).scrollTop() >= 20) {


    $('#return-to-top').fadeIn(200);
  } else {


    $('#return-to-top').fadeOut(200);
  }

});

$('#return-to-top').click(function() {
  $('body,html').animate({
    scrollTop: 0
  }, 500, 'swing');
});
#return-to-top {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 18px;
  border: none;
  outline: none;
  background-color: #777;
  color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

#return-to-top i {
  color: #fff;
  margin: 0;
  position: relative;
  font-size: 19px;
  -webkit-transition: all .3s ease;
  -moz-transition: all .3s ease;
  -ms-transition: all .3s ease;
  -o-transition: all .3s ease;
  transition: all .3s ease;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

<div style="height:700px">
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
  <p>Example text</p>
</div>
<a href="javascript:" id="return-to-top" class="btn btn-secondary">
  <i class="fa fa-angle-up"></i>
</a>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
0 голосов
/ 29 июня 2018

Вы можете сделать кнопку прокрутки вверх, как в примере ниже:

$(document).ready(function() {
  $('#autoScrl').hide();
  $("div").scroll(function() {
    $('#autoScrl').show();
  });


});

function goToTop() {
  document.getElementById('top').scrollIntoView({
    behavior: 'smooth',
    block: 'start',
    inline: 'nearest'
  });
  setTimeout(function() {
    $('#autoScrl').hide();
  }, 1000);;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
</head>

<body>

  <p>Try the scrollbar in the div</p>

  <div id='hhhh' style="border:1px solid black;width:400px;height:100px;overflow:scroll;">
    <section id="top">
      <!-- your content -->
    </section>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.' vulnerable years my father gave me some advice that I've been turning over in my mind ever
    since.
    <br><br> 'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
  </div>

  <button id='autoScrl' onclick='goToTop()'>Go To Top</button>
</body>

</html>
...