首页 > 代码库 > 获取当前视口元素

获取当前视口元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取当前视口元素</title>
    <script src="http://www.mamicode.com/script/jquery-3.2.1.min.js"></script>
</head>
<style>
    div{
        width: 800px;
        height: 200px;
        margin: 10px;
        background-color: #eee;
    }
</style>
<script>
    (function($) {
        $.expr[":"]["onScreen"] = function(elem) {
            //可视上边和下边到页头距离
            var viewTop = $(window).scrollTop();
            var viewHeight = $(window).height();
            var viewButtom = viewTop + viewHeight;

            //元素上边和下边到页头距离
            var elemTop = $(elem).offset().top;
            var elemHeight = $(elem).height();
            var elemButtom = elemTop + elemHeight;

            //元素上边或下边可见
            return (elemTop > viewTop && elemTop < viewButtom) || (elemButtom > viewTop && elemButtom < viewButtom);
            //元素单个整体可见
            return (elemTop > viewTop && elemTop < viewButtom) && (elemButtom > viewTop && elemButtom < viewButtom);
        }
    })($)
</script>
<body>
    <div><h1>1</h1></div>
    <div><h1>2</h1></div>
    <div><h1>3</h1></div>
    <div><h1>4</h1></div>
    <div><h1>5</h1></div>
    <div><h1>6</h1></div>
    <div><h1>7</h1></div>
    <div><h1>8</h1></div>
</body>
<script>
    $(window).click(function() {
        $("div").css("background-color","#eee");
        $("div").filter(":onScreen").css("background-color","#aaa");
        console.log($("div").filter(":onScreen"));
    });
</script>
</html>

  

获取当前视口元素