如何在不活动时隐藏滚动条

如何在不活动时隐藏滚动条

隐藏滚动条的方法有很多种,其中一种方法是使用onscrollonmousewheelonclickonmousemove事件,通过基本的HTML和JavaScript实现我们的目标。

步骤如下:

  • onscroll事件用于禁用滚动条。
  • onscroll事件在页面滚动时立即触发。因此,使用setTimeout()方法可以延迟隐藏滚动条,使我们能够先向下滚动。
  • 根据需要可以调整时间。
  • onmousemove事件用于在鼠标指针移动时启用滚动。onclick事件用于在用户点击时启用滚动。onmousewheel事件用于在页面向下滚动时启用滚动。因此,这些事件帮助我们在页面再次活动时启用滚动。

示例1:

一旦鼠标移动,鼠标滚动,或者用户单击,enablesrolling()函数就会被调用,从而允许我们向下滚动。当用户尝试向下滚动时,disablesrolling()函数会被调用,这会让滚动条在1000ms后消失。这个时间可能是多种多样的。要再次启用滚动条,移动鼠标指针、单击或滚动鼠标指针来调用enablesrolling()函数。文本的样式已经使用style标签完成。HTML和JavaScript代码如下所示:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title> 
        How to hide scroll bar 
        for inactivity? 
    </title> 

    <style> 
        p { 
            font-size: 2rem; 
        } 
    </style> 
</head> 

<body onscroll="disableScrolling()"
    onmousewheel="enableScrolling()"
    onclick="enableScrolling()"
    onmousemove="enableScrolling()"> 

    <p> 
        Geeks for Geeks is a Computer Science 
        Portal created with the goal of 
        providing well written, well thought 
        and well-explained solutions for 
        selected questions. Geeks for Geeks 
        has covered everything, ranging from 
        algorithms and data structure courses 
        to competitive exam preparation courses. 
        Geeks for Geeks is in true sense a 
        a haven for geeks, where Tech lovers can 
        come together and share their knowledge. 
    </p> 

    <script> 

        // JavaScript code 
        function disableScrolling() { 
            setTimeout(function() { 
                document.body.style.overflow = 'hidden'; 
            }, 1000); 
        } 

        function enableScrolling() { 
            document.body.style.overflow = ''; 
        } 
    </script> 
</body> 
</html>

输出:

如何在不活动时隐藏滚动条

示例2:这个例子隐藏了图像上的滚动条。

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title> 
        How to hide scroll bar 
        for inactivity? 
    </title> 

    <style> 
        img { 
            display: block; 
            margin-left: auto; 
            margin-right: auto; 
            width: 150%; 
        } 
    </style> 
</head> 

<body onscroll="disableScrolling()"
    onmousewheel="enableScrolling()"
    onclick="enableScrolling()"
    onmousemove="enableScrolling()"> 

    <img src= 
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191024224332/Geeksforgeeks-Paid-Online-Courses.png" alt="GfG"> 

    <script> 

        // JavaScript code 
        function disableScrolling() { 
            setTimeout(function() { 
                document.body.style.overflow = 'hidden'; 
            }, 1000); 
        } 

        function enableScrolling() { 
            document.body.style.overflow = ''; 
        } 
    </script> 
</body> 
</html>

输出:在非活动状态下隐藏滚动条的主要缺点是,一旦滚动条隐藏,body的内容就会“跳跃”并填满滚动条占用的空间。因此,它似乎对用户没有多大吸引力。

如何在不活动时隐藏滚动条

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程