How do I pass javascript events from one element to another?

◇◆丶佛笑我妖孽 提交于 2019-12-05 03:59:26
Alexis Abril

Hope I understand the OP, but you can replicate the event on any selector after the original event has occurred: http://jsfiddle.net/Cr9Kt/1/

In the linked sample, I take the event on the top layer and create a similar event fired on the bottom layer. You can take this further with any individual clicking of each element(as opposed to top and bottom as a whole).

This is a borrowed idea from another question: Triggering a JavaScript click() event at specific coordinates

I am not quite certain that I understand what you are asking for. It sound to me a bit like a tool tip. Here is an example of how to do a tooltip this using jQuery, CSS and HTML.

http://jsbin.com/ilali3/13/edit

Hope that gets you started. If you add some more details, or modify that jsbin with more details we can iterate a bit.

I updated the example a bit to include storing tool tip information into the html element itself using jQuery. This is a bit cleaner.

Bob

This may seem overly complex and inelegant...it fakes your functionality.. but it works ;)

$(document).ready(function(){
    var tileData = new Array();

    // get coordinate data for each tile
    $('div.tile').each(function(){
        var tileInfo = {};   
        tileInfo.id = this.id;
        tileInfo.text = $(this).text();
        tileInfo.width = $(this).outerWidth();
        tileInfo.height = $(this).outerHeight();
        tileInfo.position = $(this).position();
        tileInfo.coords = {};
        tileInfo.coords.top = tileInfo.position.top;
        tileInfo.coords.right = tileInfo.position.left + tileInfo.width;
        tileInfo.coords.bottom = tileInfo.position.top + tileInfo.height;
        tileInfo.coords.left = tileInfo.position.left;

        tileData.push(tileInfo);
    });

    $('div.tile').click(function(){
        $('#log').html(this.id + " clicked");
        return false;
    })       

    $('div#top').click(function(event){
        $('#log').html('Top clicked');

        // try to find tile under your mouse click
        for(i=0; i<tileData.length;i++){
            if(
                event.pageX >= tileData[i].coords.left &&
                event.pageX <= tileData[i].coords.right &&
                event.pageY >= tileData[i].coords.top &&
                event.pageY <= tileData[i].coords.bottom
            )  {
                // found a tile! trigger its click event handler
                $('#' + tileData[i].id).click();
            }
        }  

        return false;
    });
});

Try it here: http://jsfiddle.net/neopreneur/vzq4z/1/

For people stumbling on this nine years later (like I did) the best way to do this now is with the CSS pointer-events property... simply set it to 'none' for your element(s) and behold the magic. No JS required.

https://caniuse.com/#search=pointer-events

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