position: sticky

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>STICKY</title>

    <!--<script src="modernizr-dev.js"></script>-->
    <link href="index.css" rel="stylesheet" />
</head>
<body>
<header>TEST</header>
<div class="sticky-wrap">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>0</li>
        <li id="test"><div>test</div></li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>0</li>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>0</li>
    </ul>
</div>
<script>
    function featureTest( property, value, noPrefixes ) {
        // Thanks Modernizr! https://github.com/phistuck/Modernizr/commit/3fb7217f5f8274e2f11fe6cfeda7cfaf9948a1f5
        var prop = property + ':',
            el = document.createElement( 'test' ),
            mStyle = el.style;

        if( !noPrefixes ) {
            mStyle.cssText = prop + [ '-webkit-', '-moz-', '-ms-', '-o-', '' ].join( value + ';' + prop ) + value + ';';
        } else {
            mStyle.cssText = prop + value;
        }
        return mStyle[ property ].indexOf( value ) !== -1;
    }

    'use strict';
    onload = function() {
        var stickySupported = featureTest('position', 'sticky');
        document.querySelector('html').classList.add(stickySupported ? 'csssticky' : 'no-csssticky');

        if (!stickySupported) {
            var elem = document.getElementById('test');
            elem.style.height = elem.height = getComputedStyle(elem).height;
            elem.children[0].style.right = parseFloat(getComputedStyle(elem.parentElement.parentElement).width) - parseFloat(getComputedStyle(elem).width) + 'px';
            elem.parentElement.addEventListener('scroll', function() {
                console.log(this.scrollTop);
                if (this.scrollTop > elem.offsetTop) {
                    elem.classList.add('sticky');
                } else {
                    elem.classList.remove('sticky');
                }
            });
        }
    }
</script>
</body>
</html>

编程技巧