首页 > 代码库 > 获取当前视口元素
获取当前视口元素
<!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>
获取当前视口元素
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。