繁体   English   中英

如何仅运行根据屏幕大小生成“返回顶部”按钮的功能?

[英]How to only run a function that generates a "back to top" button based on screen size?

我有一个返回顶部按钮,当用户在网站上向下滚动时会出现该按钮,但是,如果此按钮仅根据屏幕大小出现,我会喜欢它。

作为 javascript 的新手,我不知道如何添加它,除了我假设它应该是“if”参数的一部分。

HTML:

<button onclick="topFunction()" id="button-top" title="Go to top">Top</button>

CSS代码:

        #button-top {
    display: none;
    position: fixed;
    bottom: 20px;
    right: 30px;
    z-index: 99;
    border: none; 
    outline: none;
    background-color: #d46900;
    color: white;
    cursor: pointer;
    padding: 15px;
    border-radius: 10px;
    font-size: 1.5em;
}

#button-top:hover {
    color: #1c1c1c;
    background-color: #ccc;
}

JS代码:

/* BACK TO TOP BUTTON*/
// 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) {
        document.getElementById("button-top").style.display = "block";
    } else {
        document.getElementById("button-top").style.display = "none";
    }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}

您应该使用媒体查询根据屏幕大小显示或隐藏您的按钮:

 /* Hide the button if the width is less than 500px */ @media (max-width: 500px) { #button-top { display: none; } }
 <button type="button" id="button-top">Back to top</button>

您可以运行上面的代码段并调整浏览器的大小,一旦宽度低于 500 像素,按钮就会消失。

不确定你想要什么。 如果您希望按钮顶部的按钮出现在桌面等大屏幕上,而在平板电脑或手机等小屏幕上消失,您可以执行以下操作:

@media only screen and (max-width: 768px) {
    #button-top {
        display: none;
    }
}

但是,如果您希望您的按钮顶部按钮在滚动后出现并在滚动回顶部后消失,您可以执行以下操作:

css:

#button-top.show {
    visibility: visible;
}

js:

$(document).on("scroll", function () {
    if ($(window).scrollTop() > 100) {
        $("#button-top").addClass("show");
    } else {
        $("#button-top").removeClass("show");
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM