javascript - 在每次点击时检查位置并添加类

标签 javascript jquery jquery-plugins

如果显示第一个或最后一个选项卡,我希望将类 .disabled 添加到左侧和/或右侧控件(.tab-left,.tab-right),以便用户可以看到他们已经到达终点并且无法再点击。

现在我喜欢这样,以防止用户越过终点。

if (tabs are at the end) {
   return;
 }

这适用于无法点击结束的用户,但如果我在返回之前添加类,问题是 .disabled 类将不会被添加,直到选项卡到达结束并且用户再次点击。

if (tabs are at the end) {
   $('.tab-right').addClass('disabled');
   return;
 }

我需要在显示最后一个选项卡时添加禁用类,而不是在用户尝试点击结束时添加。

这是 js fiddle 的链接:http://jsfiddle.net/uue6pgcx/

最佳答案

您可以尝试的一个选项是在动画完成后启用/禁用左右按钮。

$ul.filter(':not(:animated)').animate({
    "left": dir + liWidth
  }, {
    complete: function () {
    // Calculate the number of items in the container (without left and right navigation buttons).
    var lisContainer = Math.round(($container.width() - $left.outerWidth() - $right.outerWidth()) / liWidth);
    // Disable right button when list is moved to the left a number of items
    // such as the remaining number of them is less or equal than the number
    // of items that fit in the container.
    $right.toggleClass('disabled', $li.length + $ul.position().left / liWidth <= lisContainer);
    // Disable left button when list is in the origin. 
    $left.toggleClass('disabled', $ul.position().left === 0);
  }
});

免责声明:根据jQuery outerWidth additional notes , 尺寸相关 API 返回的数字,包括 .outerWidth(),在某些情况下可能是小数。代码不应假设它是一个整数。。所以希望 Math.round 足以得到正确的数字。 也许有更好的方法来计算是否必须禁用/启用右键,而不是依赖于容器中适合的项目数量。

这是经过上述修改后的代码: http://jsfiddle.net/0Lsepxeu/

关于javascript - 在每次点击时检查位置并添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26105001/

相关文章:

jQuery - 查找相对于其容器的元素索引

JQuery 颜色盒

javascript - 使用 Bootstrap 来完成我的显示/隐藏 Accordion

javascript - 为什么我无法从 Twitter 查询中的 curl_exec 获取 xml 文件的标签名称?

javascript - 将数据添加到行为对象数组 Angular 5 的末尾

jquery - 通过 jQuery 添加选中属性

javascript - 使用 .replace 将文本替换为 HTML?

jquery - 如何使用 JQuery .on() 来捕捉滚动事件

javascript - 如何通过 javascript 或 jquery 获取准确的当前城市名称?

php - Javascript 函数,如 php POST