Javascript:鼠标悬停时在dom树中获取元素

时间:2010-04-25 21:11:45

标签: javascript html dom mouseover

使用时:

document.onmouseover = function(e) {}

是否有一个属性可以让我获得dom树中的元素?

例如,我可以将样式设置为e.srcElement 但是,我如何以后访问此元素(例如)重置其样式? 我怎么知道它在dom树的哪个地方? 我希望能够将它放在整个页面转储中。

非常感谢。

为了解决稍后重新获取元素的问题,我尝试了这个但是它不起作用:

var lastelem;

document.onmouseover = function(e) {

  if (lastelem != null){
    lastelem.style.border = "0px";
  }

  if (e===undefined) e= window.event;
  var target= 'target' in event? event.target : event.srcElement;
  document.getElementById('display').value = target.tagName;
  target.style.border = "1px";
  lastelem = target;
};

由于

1 个答案:

答案 0 :(得分:3)

Which HTML element is the target of the event?(在Quirksmode.org上,由Peter-Paul Koch撰写)。另请参阅W3C DOM Level 2事件模型中的Event对象的target attribute

<!DOCTYPE html>
<html>
  <head>
    <title>target test</title>
    <style>
      *        { border: 1px solid #fff }
      .trigger { background: lightgreen }
    </style>
  </head>
  <body>
    <p class="trigger">Trigger testCase().</p>
    <p class="trigger">Trigger testCase().</p>
    <p class="trigger">Trigger testCase().</p>
    <p id="display"></p>
    <script>
var lastelem;

document.onmouseover = function (e) {
        var event = e || window.event;

        if (lastelem) {
                lastelem.style.border = "1px solid #fff";
        }

        var target = event.target || event.srcElement;
        document.getElementById('display').innerHTML = target.previousSibling.tagName +
            " | " + target.tagName + " | " + (target.nextSibling ? target.nextSibling.tagName : "X");
        target.style.border = "1px solid";
        lastelem = target;
};
    </script>
  </body>
</html>