如何仅在设备处于 xs 视图时添加点击处理程序?

How to add click handler only when the device is in xs view?

我有一个 table,在每行的第三个单元格中有一个按钮。 button/cell 隐藏在 xs 视图中,使用 twitter-bootstrap。这是示例的一个插件:http://embed.plnkr.co/Huu9UtVYChMf34uoUsAk

HTML:

<table>
  <tbody>
    <tr repeated-item ng-repeat="item in items"></tr>
  </tbody>
</table>

JS:

angular.module('test', []).directive('repeatedItem', function() {
  var lbl = $("#mylbl");
  return {
    restrict: 'A',
    replace: true,
    controller: function($scope){
      $scope.clickrow = function(){
        lbl.text('THIS SHOULD ONLY SHOW WHEN THE BUTTON IS HIDDEN (VIEW XS)');
      };
       $scope.clickbutton = function(){
        lbl.text('CLICKED BUTTON');
      };
    },
    template: '<tr ng-click="clickrow()"><td class="table-col1">Cell 1</td><td>Cell 2</td><td class="hidden-xs"><button ng-click="clickbutton()">Cell 3</button></td></tr>'
  };
});

你可以看到当window缩小时第三个单元格被隐藏了。此时,整个 TABLE 行需要变为可点击。

我的问题是 "How can I make the table row clickable only when the device is in xs view?" 我现在最好的想法是使用两个不同的 table 来完成这项工作。

我认为我可以在 table 行中使用 ng-touch 而不是 ng-click 来获得预期的结果,但是当按钮被隐藏时,这不适用于非触摸设备。

您可以在执行代码前检查屏幕分辨率。由于您使用的是 bootstrap xs 将意味着所有屏幕都低于 768px (http://getbootstrap.com/css/#grid)。

要检查在您的指令中添加 $window

var windowWidth = $window.outerWidth;

if (windowWidth <= 768) {
   // Execute code
}

而不是 controller 使用 link,这样您就可以定位 elem。现在,当用户单击该行时,仅当按钮隐藏时标签才会出现(意味着用户处于移动视图中)。为此,我们检测按钮是否可见。

使用此方法,可以在您的 CSS 文件中设置网格宽度,因此您的设计问题不会泄漏到您的 JavaScript 代码中。所以你永远不必更新 JS 代码来设置新的宽度。

.directive('repeatedItem', function() {
  var lbl = $("#mylbl");
  return {
    restrict: 'A',
    replace: true,
    template: '<tr ng-click="clickrow()"><td class="table-col1">Cell 1</td><td>Cell 2</td><td class="hidden-xs"><button ng-click="clickbutton()">Cell 3</button></td></tr>',
    link: function (scope, elem, attrs) {

      scope.clickrow = function ($event) {
        var isButtonVisible = elem.find('button:visible').length;
        var isRowClickAllowed = isButtonVisible === 0;

        if (isRowClickAllowed) {
            alert('Row click event was triggered!');
        } else {
            console.log('Row click event was triggered, but we did nothing, because the button is visible and accessible.');
        }
      };

      scope.clickbutton = function (){
        alert('Button click was triggered!');
      };
    }
  };