Javascript - div里面的div问题

时间:2011-04-16 20:30:04

标签: javascript html

当鼠标离开hideall()时,我需要执行id1函数。使用下面的代码,它会正确调用hideall(),但当鼠标移出id2时会再次调用它。

<div id="id1" onmouseout="hideall();" style="border:1px solid red;">
          <div id="id2">This is inside id1 div</div>
</div>

http://i.stack.imgur.com/hrfsM.png

2 个答案:

答案 0 :(得分:1)

Internet Explorer中有一个名为鼠标假的专有事件,我相信这正是您所寻找的。不幸的是,这不适用于所有浏览器。我建议你使用像jQuery这样的javascript库。它内置了事件。有关详细信息,请参阅http://api.jquery.com/mouseleave/。所以你可能会想要的是这样的:

<div id="id1" style="border:1px solid red;">
      <div id="id2">This is inside id1 div</div>
</div>
<script>
$(document).ready(function() {
    $('#id1').mouseleave(function() {
        hideAll();
        // Or whatever else you want to do when the mouse leaves the element.
    });
});
</script>

答案 1 :(得分:0)

改编我的另一个答案previously

<div id="id1" onmouseout="showTarget('id1',0);" onmouseover="showTarget('id1',1);" style="border:1px solid red; width: 150px; height: 100px">
 <div id="id2" onmouseover="showTarget('id1',1);" onmouseout="showTarget('id1',1);" style="background-color: red; color: white; width: 100px; height: 75px;">This is inside id1 div</div>
</div>

function showTarget(target, state) {
    switch (state) {
        case 1:
            state = 'block';
        break;
        default:
            state = 'none';
    }
    console.log(state);
    document.getElementById(target).style.display = state;
}

http://jsfiddle.net/gMpkX/