1. 程式人生 > >div內的scroll區域性滾動

div內的scroll區域性滾動

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    *{
    	padding: 0;
    	margin: 0;
    }
    .box {
        width: 300px;
        height: 200px;
        overflow: auto;
        background: red;
        margin: auto;
        top: 100px;
        position: relative;
    }

    .auo {
        width: 100%;
        height: 1000px;
        background: yellow;
    }

    .hh {
        width: 100%;
        height: 50px;
        text-align: center;
        background: green;
    }
    </style>
</head>

<body>
    <div class="box">
        <div class="auo">
            22222222222222
            <div class="hh">1</div>
            <div class="hh">2</div>
            <div class="hh">3</div>
            <div class="hh">4</div>
            <div class="hh">5</div>
            <div class="hh">6</div>
            <div class="hh">7</div>
            <div class="hh">8</div>
            <div class="hh">9</div>
            <div class="hh">10</div>
            <div class="hh">11</div>
            <div class="hh">12</div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script>
    window.onunload = function() {
        return confirm("Are you sure you want to leave this page?");
    };
    $('.box').on('scroll', function(e) {
        console.log(e,'區域性滾動'); 
    });
    setTimeout(gf, 2000);
    aaa($('.box'),$('.hh'),6,-100);
    /**
     * 動態改變dom位置
     * @param  {[type]} parentDom [滾動區域父元素]
     * @param  {[type]} listDom   [滾動的列表]
     * @param  {[type]} index     [滾動到的指定元素]
     * @param  {[type]} offset    [便宜正上方的量,上負下正]
     * @return {[type]}           [description]
     */
    function aaa(parentDom,listDom,index,offset){    	
    	offset=typeof offset=='undefined'?0:offset;
    	let ll=listDom.eq(index).position().top;
    	if(parentDom.scrollTop()){
    		parentDom.scrollTop(ll+parentDom.scrollTop()-offset);
    	}else {
    		parentDom.scrollTop(ll-offset);
    	};
    }
    function gf() { //高度變化函式呼叫獲取dom位置方法
        $('.hh').height(100);
       aaa($('.box'),$('.hh'),8,-100);
    }
    </script>
</body>

</html>