index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // components/TopTabbar/index.js
  2. Component({
  3. /**
  4. * 组件的属性列表
  5. */
  6. properties: {
  7. tabList: {
  8. type: Array,
  9. value: []
  10. },
  11. border: {
  12. type: Boolean,
  13. value: true
  14. },
  15. tabIndex: {
  16. type: Number,
  17. value: 0
  18. },
  19. },
  20. observers: {
  21. tabIndex: function (n) {
  22. this.click(n);
  23. },
  24. },
  25. /**
  26. * 组件的初始数据
  27. */
  28. data: {
  29. tabDataIndex: 0,
  30. scroll_width: 0,
  31. scroll_left: 0
  32. },
  33. lifetimes: {
  34. attached: function () {},
  35. detached: function () {},
  36. },
  37. pageLifetimes: {
  38. // 组件所在页面的生命周期函数
  39. show: function () {
  40. this.onLoad();
  41. },
  42. hide: function () {},
  43. resize: function () {},
  44. },
  45. /**
  46. * 组件的方法列表
  47. */
  48. methods: {
  49. onLoad() {
  50. var that = this;
  51. that.createSelectorQuery().select('#topTabbar-item').boundingClientRect(function (res) {
  52. try {
  53. that.setData({
  54. scroll_width: res.width
  55. })
  56. } catch (e) {}
  57. }).exec();
  58. },
  59. changeType(e) {
  60. var that = this;
  61. if (this.data.tabDataIndex == e.currentTarget.dataset.index) return;
  62. let index = e.currentTarget.dataset.index;
  63. let item = e.currentTarget.dataset.item;
  64. let offsetLeft = e.currentTarget.offsetLeft;
  65. let scroll_left = this.data.scroll_left;
  66. that.createSelectorQuery().select('#topTabbar_select_' + index).boundingClientRect(function (res) {
  67. // //console.log(res)
  68. scroll_left = offsetLeft - that.data.scroll_width / 2 + (res.width / 2);
  69. that.setData({
  70. tabDataIndex: index,
  71. scroll_left: scroll_left
  72. });
  73. that.triggerEvent('change', {
  74. index,
  75. item
  76. })
  77. }).exec();
  78. },
  79. click(eindex) {
  80. var that = this;
  81. if (this.data.tabDataIndex == eindex) return;
  82. let index = eindex;
  83. let item = this.data.tabList[eindex];
  84. let scroll_left = this.data.scroll_left;
  85. that.createSelectorQuery().select('#topTabbar_select_' + index).boundingClientRect(function (res) {
  86. scroll_left = res.left - that.data.scroll_width / 2 + (res.width / 2);
  87. that.setData({
  88. tabDataIndex: index,
  89. scroll_left: scroll_left
  90. });
  91. that.triggerEvent('change', {
  92. index,
  93. item
  94. })
  95. }).exec();
  96. }
  97. }
  98. })