Click Entire Row (preserving middle click and ctrl+click)

后端 未结 10 1216
独厮守ぢ
独厮守ぢ 2020-12-07 20:49

I have an HTML table with a link in the first column. I want to allow the user to click anywhere in the row to activate that link. At the same time, I would like to preser

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 21:22

    Unfortunately there is no way to simulate a link and all associated behaviour in every browser. Therefore, the only way to achieve what you want is to have a link that follows the cursor around the element; this link would be invisible so, to the user, it looks like they're clicking on the but they're actually clicking on a hidden link. Using this method, the middle-button, ctrl+click and any other behaviours are left intact!

    Here's a DEMO: http://jsbin.com/ufugo

    And here's the code:

    $("table tr").each(function(){
    
        var $link = $('a:first', this).clone(true),
            dim = {
                x: [
                    $(this).offset().left,
                    $(this).offset().left + $(this).outerWidth()
                ],
                y: [
                    $(this).offset().top,
                    $(this).offset().top + $(this).outerHeight()
                ]
            }
    
        $link
            .click(function(){
                $(this).blur();
            })
            .css({
                position: 'absolute',
                display: 'none',
                // Opacity:0  means it's invisible
                opacity: 0
            })
            .appendTo('body');
    
        $(this).mouseover(function(){
            $link.show();
        });
    
        $(document).mousemove(function(e){
            var y = e.pageY,
                x = e.pageX;
            // Check to see if cursor is outside of 
            // If it is then hide the cloned link (display:none;)
            if (x < dim.x[0] || x > dim.x[1] || y < dim.y[0] || y > dim.y[1]) {  
                return $link.hide();
            }
            $link.css({
                top: e.pageY - 5,
                left: e.pageX - 5
            })
        });
    
    });
    

    EDIT:

    I created a jQuery plugin using a slightly better aproach than above: http://james.padolsey.com/javascript/table-rows-as-clickable-anchors/

提交回复
热议问题