前端小记

获取屏幕内所有元素

此处演示只后去文本元素

function isElementInViewport(el) {
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
};
var visibleEles = new Array();
function findVisibleElement(el, containerArray) {
    // console.log("type = " + Object.prototype.toString.call(el));
    var array = el.childNodes;
    if (array.length < 1 ) {
        // 去除不需要的 dom style
        if (Object.prototype.toString.call(el) === '[object Text]') {
            var parentnode = el.parentNode;
            if (Object.prototype.toString.call(parentnode) === '[object HTMLScriptElement]'
            ||
            Object.prototype.toString.call(parentnode) === '[object HTMLHeadElement]'
            ||
            Object.prototype.toString.call(parentnode) === '[object HTMLStyleElement]'
            ||
            Object.prototype.toString.call(parentnode) === '[object HTMLBodyElement]' 
            ) {
                return;
            }
            // 过滤空文本
            var content = parentnode.textContent;
            if (content == null || content.length <= 0) {
                // console.log('空字符串');
                return ;
            }
            console.log(parentnode.innerText);
            var iscontain = isElementInViewport(parentnode);
            // console.log(iscontain? "-- 内":"-- 外");       
            if (iscontain) {
                containerArray.push(content);
            }
        }
    } else {
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            this.findVisibleElement(element, containerArray);
        }
    }
}
findVisibleElement(document.documentElement, visibleEles);
visibleEles.join("");
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,704评论 1 92
  • 盒子大小包括 margin,border,padding,本身大小 竖直高度= height + padding-...
    五月笑忘阅读 1,261评论 0 1
  • 一、多个网页共用相同网页头部和尾部方法(以尾部为例且以下方式的普适性有待考证): 1.写一个规范的html结构网页...
    我是阿木呀阅读 5,430评论 0 0
  • “简单地记一下这段时间所遇到的前端知识点”1.用于重新计算iframe高度 2.PC端窗口缩放,页面布局不发生改变...
    xpwei阅读 2,682评论 0 1
  • 浏览网页时点击登录弹出登录框后,之前的网页会被虚化,这是遮罩层在发挥作用。 实现方式如下(重点配置遮罩层): 1....
    我是阿木呀阅读 5,692评论 0 1

友情链接更多精彩内容