用js实现chrome中css选择器路径生成

gg22g2

因为想要尽可能和chrome生成的结果一致,加了很多判断条件

function cssSelector(element) {

    if (element.id != undefined && element.id != ""  ) {
        let d = element.id[0];
        //判断id是不是数字开头
        if (d != "0" && d != "1" && d != "2" && d != "3" && d != "4" && d != "5" && d != "6" && d != "7" && d != "8" && d != "9") {
            return "#" + element.id;
        } else {
            //数字开头打id 需要\3+对应数字+ (英文空格)+其余内容
            return "#\\3" + d + " " + element.id.substr(1, element.id.length)
        }
    }
    let nodeName = element.nodeName.toLowerCase();
    let select = nodeName;
    let classuffix = "";
    let classList = element.classList;
    //拼接class
    if (classList.length > 0) {  //排除附加的class,其余的拼接起来
        classuffix += classList[0] != greedColor ? "." + classList[0] : "";
        for (let i = 1; i < classList.length; i++) {
  
                classuffix += "." + classList[i];

        }
    }
    let tempselect = select + classuffix;
    if (element.parentNode === document.body) { //遍历到顶了,直接返回
        return tempselect;
    }

    //这里有bug 可能会访问parentNode下的所有元素而非子元素
    let sameElements = element.parentNode.querySelectorAll(tempselect); //验证生成的css选择器筛选结果是否唯一
    const p = element.parentNode
    let count1 = 0, count2 = 0;
    sameElements.forEach(function (child) {
        if (child.parentNode === p && child.nodeName === element.nodeName) {
            count1++;

        }
    })
    for (let i = 0; i < p.children.length; i++) {
        if (p.children[i].nodeName === element.nodeName) {
            count2++;
        }
    }

    if (count1 > 1) {  //结果不唯一,需不需要加nth-child
        if (count1 === count2) {  //如果在element兄弟元素中,和element类型相同的标签,样式都一样 不需要class作为筛选条件
            select = nodeName + ":nth-child(" + elementSiblingIndex(element.parentNode.children, element) + ")"
        } else {    //正常拼接
            select = tempselect + ":nth-child(" + elementSiblingIndex(element.parentNode.children, element) + ")"
        }
    } else if (count1 === 1) { //结果唯一 则判断不加class选择器是否还唯一
        const count3 = querySameElementCount(element);
        if (count3 === 1) {  //只需要用标签名就可以准确找到该元素
            select = nodeName;
        } else if (count3 > 1) { //单独用标签名不够作为筛选条件
            select = tempselect;
        }
    }
    //生成父元素css前,加>符号,代表父子关系
    select = " > " + select;
    return cssSelector(element.parentNode) + select;
}

function querySameElementCount(element) {
    const children = element.parentNode.children;
    let count = 0;
    const nodeName = element.nodeName;
    for (let i = 0; i < children.length; i++) {
        if (children[i].nodeName == nodeName) {
            count++;
        }
    }
    return count;
}


function elementSiblingIndex(elements, search) {
    let length = elements.length;
    for (let i = 0; i < length; i++) {
        if (elements[i] === search) {
            return i + 1;
        }
    }
}
阅读 886
223 声望
5 粉丝
0 条评论
223 声望
5 粉丝
文章目录
宣传栏