Моя кнопка «назад к началу» работает правильно. Тем не менее, кнопка отображается в верхней части страницы, которую я хочу скрыть и отобразить после 20 прокруток. Я использую пример из школ W3. Это выдает ошибку, когда я использую его в своем коде. Как это исправить?
Error
> (index):115 Uncaught TypeError: Cannot read property 'style' of null
at scrollFunction ((index):115)
at window.onscroll ((index):108)
scrollFunction @ (index):115
window.onscroll @ (index):108
Вот мой CSS:
#myBtn {
width: 3rem;
height: 3rem;
align-items:center !important;
}
#myBtn svg {
fill: #000;
display: block !important;margin: auto !important;
}
Мой Javascript такой, как показано ниже:
/** Scroll back-to-top */
//Get the button
var mybutton = document.getElementById("myBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
var url = window.location.href;
var index = url.lastIndexOf("/") + 1;
var filename = url.substr(index);
if (filename == "index.html") {
$("top").hide() ;
};
Это мой HTML где я определяю свою кнопку.
<button class="myBtn" type="button" aria-label="Back to Top" style="float:right;" onclick="topFunction()" id="myBtn">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 32 32" aria-hidden="true" style="will-change: transform;">
<path d="M16 14L6 24 7.4 25.4 16 16.8 24.6 25.4 26 24zM4 8H28V10H4z"></path></svg></button>