Сделать весь блок div ссылкой, строку tr таблицы ссылкой

Сделать весь блок div ссылкой, строку tr таблицы ссылкой Как сделать всю строку таблицы (<tr>) кликабельной, как ссылка?

Можно бы сделать вот так:

$('tr').bind('click', function(){
    window.location = 'http://somelocation.com';
    // Or, we can grab the HREF from the first anchor:
    // window.location = $('a:first', this).attr('href');
});

Но это не реальная ссылка! Браузеры же дают большие возможности ссылка:

  • Middle-click: открыть в новой вкладке.
  • CTRL/SHIFT: в новом окне.
  • Right-click options: “открыть в новом окне”, “копировать ссылку” и др.
  • В статусной строке видим путь ссылки.
  • и др…

Невозможно всё это искусственно симулировать. Пользователям не понравится, если ссылка ведёт себя не так, как от неё ждут…

Нет правил, что строки таблиц или div не могут быть кликабельными, но если вы собираетесь их такими сделать, то нужно добиться того, чтобы они вели себя как обычные ссылки. Конечно, большинство пользователей не думают, что это ссылки; это просто переходы на другие страницы, но сложено представление, что они ведут себя как ссылки, и это представление не стоит обманывать.

Другими словами, если хотите сделать элемент ссылкой, сделайте точнейшую эмуляцию ссылки.

Вот jQuery plugin, обеспечивающий это дело (superlink.jquery.js):
(function($){
    
    /* ----
       superLink jQuery plugin
       (c) James Padolsey
       ----
       Contributors:
            Brian Fisher
    */
    
    $.fn.superLink = function(link) {
        link = link || 'a:first';
        return this.each(function(){
            
            var $container = $(this),
                $targetLink = $(link, $container).clone(true);
            
            /* Take all current mouseout handlers of $container and
               transfer them to the mouseout handler of $targetLink */
            var mouseouts = $(this).data('events') && $(this).data('events').mouseout;
            if (mouseouts) {
                $.each(mouseouts, function(i, fn){
                    $targetLink.mouseout(function(e){
                        fn.call($container, e);
                    });
                });
                delete $(this).data('events').mouseout;
            }
            
            /* Take all current mouseover handlers of $container and
               transfer them to the mouseover handler of $targetLink */
            var mouseovers = $(this).data('events') && $(this).data('events').mouseover;
            if (mouseovers) {
                $.each(mouseovers, function(i, fn){
                    $targetLink.mouseover(function(e){
                        fn.call($container, e);
                    });
                });
                delete $(this).data('events').mouseover;
            }
            
            $container.mouseover(function(){
                $targetLink.show();
            });
            
            $targetLink
                .click(function(){
                    $targetLink.blur();
                })
                .mouseout(function(e){
                    $targetLink.hide();
                })
                .css({
                    position: 'absolute',
                    top: $container.offset().top,
                    left: $container.offset().left,
                    /* IE requires background to be set */
                    backgroundColor: '#FFF',
                    display: 'none',
                    opacity: 0,
                    width: $container.outerWidth(),
                    height: $container.outerHeight(),
                    padding: 0
                })
                .appendTo('body');
                
        });
    };
    
})(jQuery);

вот как можно его подключить:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
    <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title>&quot;superLink&quot; DEMO</title>
    
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js"></script>
            <script type="text/javascript" src="superlink.jquery.js"></script>
            <style type="text/css">
                body {background:#EEE;color:#222;font:0.8em Arial,Verdana,Sans-Serif;margin:0;padding:20px;}
                div#contain {width: 946px; margin: 0 auto;}
                div.block {width:250px; background:white; display:inline;border: 2px solid #222; padding: 20px; float: left; margin: 10px;}
                h1 {
                    margin: 0 10px;
                    padding: 10px 0 0 0 ;
                }
                p { margin: 20px 10px; clear:both;  }
                div.block p {margin: 0;}
                table,tr {
                    border-collapse: collapse;
                }
                #table {width: 100%; float: left;}
                table { clear:both; margin: 20px 10px; }
                td {
                    padding: 6px 18px;
                    background: #DDD;
                    border: 1px solid #222;
                }
                #contain div.active {background: #F39429; }
                tr.active td {background: #FFFE9F; }
            </style>
    </head>
    <body>
        <div id="contain">
            <div class="block">
                <a href="http://google.com">Google link</a>
                <p>Aliquam pulvinar tortor sed arcu vulputate pulvinar. Curabitur vestibulum, diam sit amet sollicitudin gravida, velit sapien euismod tortor, ut rhoncus dolor libero id dui. Mauris ac leo erat. Duis ac accumsan ante. Etiam sapien nunc, tincidunt sed consequat eget, imperdiet at nulla. Nullam rutrum bibendum viverra.</p>
            </div>
            
        <div id="table">
       <table>
          <tr>
            <td><a href="http://google.com">Google</a></td>
            <td>Normal text</td>
            <td>Normal text</td>
            <td>Normal text</td>
            <td>Normal text</td>
           <td>Normal text</td>
          </tr>
          <tr>
            <td><a href="http://yahoo.com">Yahoo</a></td>
            <td>Normal text</td>
            <td>Normal text</td>
            <td>Normal text</td>
           <td>Normal text</td>
            <td>Normal text</td>
          </tr>
        </table>
        </div>
            
        </div>
  
        <script type="text/javascript">
            $('div.block')
                .mouseover(function(){
                    $(this).addClass('active');
                })
                .mouseout(function(){
                    $(this).removeClass('active');
                })
                .superLink();
            $('tr')
                .mouseover(function(){
                    $(this).addClass('active');
                })
                .mouseout(function(){
                    $(this).removeClass('active');
                })
                .superLink();
        </script>
        
    </body>
</html>

Он работает для любого элемента, содержащего ссылку.

Использовать плагин очень просто; например, у вас есть таблица с несколькими строками; в каждой строке есть ссылка в последнем столбце <td>:

$('table#mytable tr').superLink('a:last');

Так каждая строка будет казаться пользователю одним гигантским якорем!


То есть:

  1. подключить в head или в конце страницы - superlink.jquery.js
  2. в футер вставить <script>
  3. добавить класс .block к блоку, который надо сделать ссылкой

almix
Разработчик Loco, автор статей по веб-разработке на Yii, CodeIgniter, MODx и прочих инструментах. Создатель Team Sense.

Вы можете почитать все статьи от almix'а.



Другие статьи по этой теме:

Комментарии (1)     Подпишитесь на RSS комментариев к этой статье.

1 комментарий

#462
Данил говорит:
May 20, 2012 at 12:57 am
Спасибо за статью.