js代码,鼠标在页面点击时,记录元素的Xpath
代码:
function mouse_down(event){ var x = event.clientX, y = event.clientY var element = document.elementFromPoint(x, y) if (!element) { console.log("error: no element") } console.log(readXPath(element)) } function readXPath(element) { count = 1 result = "" while (true){ count += 1 if(count>99){ break } if (element == document.body){ console.log('/html/body/' + result) break } else { tag_index = 0 tmp = element.parentElement for(var i=0;i<tmp.childElementCount;i++){ if (tmp.children[i].tagName == element.tagName){ tag_index += 1 } if (element == tmp.children[i]){ result = element.tagName.toLowerCase() + "[" + String(tag_index) + "]" + "/" +result // console.log(result) break } } element = tmp } } } document.onmousedown = mouse_down