baozhuangscript3.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. function readXPath(element) {
  2. if (element.id !== "") {//判断id属性,如果这个元素有id,则显 示//*[@id="xPath"] 形式内容
  3. return '//*[@id=\"' + element.id + '\"]';
  4. }
  5. //这里需要需要主要字符串转译问题,可参考js 动态生成html时字符串和变量转译(注意引号的作用)
  6. if (element == document.body) {//递归到body处,结束递归
  7. return '/html/' + element.tagName.toLowerCase();
  8. }
  9. var ix = 1,//在nodelist中的位置,且每次点击初始化
  10. siblings = element.parentNode.childNodes;//同级的子元素
  11. for (var i = 0, l = siblings.length; i < l; i++) {
  12. var sibling = siblings[i];
  13. //如果这个元素是siblings数组中的元素,则执行递归操作
  14. if (sibling == element) {
  15. return arguments.callee(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix) + ']';
  16. //如果不符合,判断是否是element元素,并且是否是相同元素,如果是相同的就开始累加
  17. } else if (sibling.nodeType == 1 && sibling.tagName == element.tagName) {
  18. ix++;
  19. }
  20. }
  21. };
  22. var nodeList = [];
  23. NowNode = null;
  24. var xnode = null;
  25. var style = ""; //记录上个元素的颜色
  26. document.addEventListener("mousemove", function () {
  27. oe = document.elementFromPoint(event.x, event.y);
  28. NowNode = oe;
  29. console.log(oe);
  30. if (xnode == null) {
  31. xnode = oe;
  32. }
  33. if (xnode != oe) {
  34. xnode.style.backgroundColor = style; //上个元素改回原来元素的背景颜色
  35. style = oe.style.backgroundColor;
  36. exist = 0;
  37. for (o of nodeList) {
  38. if (o["node"] == oe) {
  39. exist = 1;
  40. break;
  41. }
  42. }
  43. if (exist == 1) {
  44. }
  45. else {
  46. oe.style.backgroundColor = '#DDDDFF'; //设置新元素的背景元素
  47. }
  48. xnode = oe;
  49. }
  50. //对于可点击元素,屏蔽点击事件
  51. if (oe.style.cursor == "pointer" || oe.tagName == "A" || oe.tagName == "BUTTON" || oe.tagName == "INPUT" || oe.onclick) {
  52. oe.setAttribute("disabled", true);
  53. }
  54. });
  55. document.addEventListener("click", function () {
  56. nodeList.push({ node: NowNode, bgcolor: style, xpath: readXPath(NowNode) });
  57. NowNode.style.backgroundColor = "#80FFFF";
  58. style = "#80FFFF";
  59. console.log(nodeList);
  60. //对于可点击元素,屏蔽a标签默认点击事件
  61. event.stopImmediatePropagation();
  62. event.stopPropagation();
  63. event.preventDefault ? event.preventDefault() : event.returnValue = false;
  64. });
  65. //清除选择项
  66. function clear() {
  67. //如果最后停留的元素被选中,则调整此元素的style为原始style,否则不进行调整
  68. for (node of nodeList) {
  69. node["node"].style.backgroundColor = node["bgcolor"];
  70. if (NowNode == node["node"]) {
  71. style = node["bgcolor"];
  72. }
  73. }
  74. nodeList.splice(0, nodeList.length); //清空数组
  75. }