面试题-输出所有页面宽度和高度大于 50 像素的节点

问题描述:

写一个 traverse 函数,输出所有页面宽度和高度大于 50 像素的节点

问题解析

先获取所有的元素节点,分别得到他们的页面宽与高,输出元素页面宽与高大于50的元素节点

解决方案:

普通版:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>测试</h1>
    <table width="100" height="100" border="2" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                <form name="form1" action="" method="post">
                    <input type="text" name="ipput1" value="测试">
                    <br />
                    <input type="password" name="password" value="">
                </form>
            </td>
        </tr>
    </table>
    <div id="demo"></div>
</body>
<script>
    function traverse() {
        // 定义一个放结果的空数组arr
        var arr = [];
        // 所有节点标签放到elements[]中去
        var elements =[];
        if(document.all){
            elements = document.all;
        }else{
            elements = document.getElementsByTagName("*")
        }
        console.log(elements.length)
        // 获取到elements[i]的页面宽与高
        for(var i=0;i<elements.length;i++){
            var ele = elements[i]
            var width = parseFloat(ele.style.width)||ele.offsetWidth;
            var height = parseFloat(ele.style.height)||ele.offsetHeight;
            // 页面宽与高大于50的放进arr数组内
            if(width > 50&&height>50){
                arr.push(elements[i].tagName);
            }  
        }
        return arr;
    }
    window.onload = function () {
        console.log(traverse())
        
    }
</script>
</html>

优化版:

function traverse(){
    return Array.prototype.filter.call(document.querySelectorAll('body *'), function(node){
        return node.offsetWidth > 50 && node.offsetHeight > 50;
    });
}
上一篇:Python for Data Science - Defining elements of a plot


下一篇:LeetCode #1608. Special Array With X Elements Greater Than or Equal X