获取屏幕内所有元素
此处演示只后去文本元素
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("");