如何使用jQuery改变滚动元素的风格

如何使用jQuery改变滚动元素的风格

我们给出了一个包含一些CSS属性的HTML文档,任务是使用jQuery改变页面滚动后某个元素的CSS属性。为了改变元素在滚动时的样式,我们要得到一个元素的内容在水平或垂直方向上被滚动的像素数。

下面的例子说明了如何在元素滚动时改变它们的样式。改变元素滚动时的样式的一个方法是改变元素所属的类。

示例:

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to change style of elements 
        on scroll using jQuery?
    </title>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
  
    <style>
        .classinitial {
            height: 200px;
            background-color: rgba(255, 255, 255, 0.5);
            position: fixed;
            top: 200;
            width: 100%;
            transition: all 0.5s;
            background-clip: border-box;
            border-width: 5px;
            border-style: solid;
        }
  
        .classfinal {
            height: 100px;
            background-color: rgba(0, 0, 0, 0.8);
            position: fixed;
            top: 200;
            width: 100%;
            transition: all 0.5s;
            border-width: 8px;
            border-style: solid;
        }
  
        .wrapper {
            height: 2000px;
            padding-top: 200px;
            color: green;
            text-align: center;
            font-size: larger;
            font-weight: bold;
        }
    </style>
</head>
  
<body>
    <header class="classinitial"></header>
    <div class="wrapper">
        Geeks For Geeks
    </div>
  
    <script>
        (function () {
            var header =(".classinitial");
            (window).scroll(function () {
                var scroll =(window).scrollTop();
  
                if (scroll >= 155) {
                    header.removeClass('classinitial')
                            .addClass("classfinal");
                } else {
                    header.removeClass("classfinal")
                            .addClass('classinitial');
                }
            });
        });
    </script>
</body>
  
</html>

上述代码在CSS样式属性的帮助下为初始类和最终类(根据代码称为classinitial和classfinal)添加样式。下面是帮助改变html代码中存在的标题元素的类别的JavaScript代码。

如果页面被垂直滚动了155像素,jQuery代码将标题元素的类从classinitial翻转到classfinal。否则,它将类从classfinal翻转到classinitial。为此,jQuery的addClass()和removeClass()方法被用于上述代码中。在这里,scrollTop()函数被用来获取元素被滚动的像素数,并被保存在名为scroll的变量中。

输出:

如何使用jQuery改变滚动元素的风格?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程