开发者

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

开发者 https://www.devze.com 2023-01-23 05:53 出处:网络
I have this interface I want to build using Effect.Move from scriptaculous (with Prototype, of course).

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', f开发者_如何学Cunction(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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消