固定范围内的随屏滚动

作者:可乐 发布时间:November 3, 2016 分类:前端 No Comments

09年的时候,在blueidea上问过这个问题,那时候没人回我。最近在那看到有人问,顺手写一下吧。

<textarea name="rtext" class="run_code" id="runcode_31682"><!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Document</title>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.slim.min.js"></script>

</head>
<body>

<style type="text/css">
    .box{ position: relative; margin: 10px; margin-bottom: 100px; border: 1px solid #CCC; }
    .pic{ position: absolute; left: 20px; top: 20px; width: 60px; height: 60px; background-color: #F00; text-align: center; line-height: 60px; font-size: 30px; color: #FFF }
    .fixed{ position: fixed; left: 39px; top: 31px; }
    .bottom{ position: absolute; top: auto; left: 20px; bottom: 20px; }
</style>
<div class="box" style="height: 1500px;">
    <div class="pic">1</div>
</div>
<div class="box" style="height: 500px;">
    <div class="pic">2</div>
</div>
<div class="box" style="height: 1800px;">
    <div class="pic">3</div>
</div>
<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('.box').each(function(index, el) {
            var _self = $(this)
            var boxHeight = $(this).outerHeight();
            $(window).on('scroll', function(event) {
                if (el.getBoundingClientRect().top < 0) {
                    boxHeight + el.getBoundingClientRect().top - 100 < 0 ? _self.find('.pic').addClass('bottom') : _self.find('.pic').removeClass('bottom').addClass('fixed')    
                }else{
                    _self.find('.pic').removeClass('fixed')
                }
            });
        });
    });
</script>

</body>
</html></textarea>
<input class="btn btn-primary" name="rbutton" type="button" onclick="runcode('runcode_31682');" value="运行代码">

标签: none

评论已关闭