Mouseover event triggered by Child Elements - how to stop this?

梦想的初衷 提交于 2019-12-24 00:45:31

问题


I have this interface I want to build using Effect.Move from scriptaculous (with Prototype, of course).

When the top div is triggered on a mouseover, a span tag is to move 50 pixels to the left - and reset without movement to the original location on mouseout. The problem is, any time this div element is entered from a child element, the element I want moved moves an additional 50 pixels. I've tried using relatedTarget and toElement to stop this event from propogating, but to no avail. Here is the code, as of yet incomplete:

e.observe('mouseover', function(evt) {
   var block = e.down('span');

   if(evt.target == block && !evt.relatedTarget.descendantOf(block)){
    new Effect.Move(block, { x: -50, duration: 0.4, 

    });
   } else {

   }

  });

HTML Sample:

<div class='trigger'>
  <span class='to-be-moved'>...</span>
  <p>Child Element</p>
  <h2>Another Child Element</h2>
  <a>Link</a>
</div>

I'm totally lost here - any suggestions?


回答1:


Did you try to use "mouseenter" and "mouseleave" instead of "mouseover" and "mouseout"? They will only trigger once even with child elements, and Prototype supports it since 1.6.1.




回答2:


Try this function

function hover(elem, over, out){
    $(elem).observe("mouseover", function(evt){
        if(typeof over == "function"){
            if(elem.innerHTML){
                if(elem.descendants().include(evt.relatedTarget)){ return true; }
            }
            over(elem, evt);
        }else if(typeof over == "string"){
            $(elem).addClassName(over);
        }
    });
    $(elem).observe("mouseout", function(evt){
        if (typeof out == "function") {
            if(elem.innerHTML){
                if(elem.descendants().include(evt.relatedTarget)){ return true; }
            }
            out(elem, evt);
        }else if(typeof over == "string"){
            $(elem).removeClassName(over);
        }
    });
    return elem;
}

Usage is:

hover($('el_id'), function(elem, evt){
    /* Mouse over code here */
},
function(elem, evt){
    /* Mouse out code is here */
});

It's very simple.




回答3:


Look here.

If you're looking for a specific element that triggered the onmouseover event, use Prototype's Event.findElement(...) method in order to sift through unwanted children.

Serkan's answer is a hoky way of completing the task but won't work in all browsers.



来源:https://stackoverflow.com/questions/4095546/mouseover-event-triggered-by-child-elements-how-to-stop-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!