因此,在我的代码中,当您单击一个元素时,它将发现该元素的路径并提醒它。我想然后“保存”元素的路径,然后单击按钮,找到它并为其添加红色边框。
function nodelistToArray(nodelist) {
return Array.prototype.slice.call(nodelist);
}
function traverse(target, chain) {
if (chain === void 0) {
chain = [];
}
var index = nodelistToArray(target.parentNode.children).filter(function(a) {
return a.nodeName == target.nodeName;
}).indexOf(target);
chain.push({
element: target,
index: index
});
if (target.nodeName.toLowerCase() == "html") {
return chain.reverse();
} else {
return traverse(target.parentNode, chain);
}
}
document.addEventListener("click", eOnClick, true);
function eOnClick(evt) {
var chain = traverse(evt.target);
alert(chain.map(function(elm) {
return elm.element.nodeName + ' [' + (elm.index).toString() + ']';
}).join(' > '));
}
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
<p>1. Click one of the elements above
<br>2. An alert will tell you where this element is located
<br>3. Click the button below to add a red border to the element
<p><button>Click Me</button>
答案 0 :(得分:0)
不要认为需要找出元素的路径。你可以得到这样的元素 并申请css。
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
target.setAttribute('style','border:10px solid red');
}, false);