如何为font-size制作自定义范围滑块?

时间:2017-05-05 15:58:05

标签: javascript angularjs

我有一个场景,因为我必须使用范围滑块来显示字体大小,但我有一个普通的滑块,我需要在它滑动时在工具提示上显示字体大小。

JS:

angular.module('textSizeSlider', [])
  .directive('textSizeSlider', ['$document', function ($document) {
    return {
      restrict: 'E',
      template: '<div class="text-size-slider"><span class="small-letter" ng-style="{ fontSize: min + unit }">A</span> <input type="range" min="{{ min }}" max="{{ max }}" step="{{ step || 0 }}" ng-model="textSize" class="slider" value="{{ value }}" /> <span class="big-letter" ng-style="{ fontSize: max + unit }">A</span></div>',
      scope: {
        min: '@',
        max: '@',
        unit: '@',
        value: '@',
        step: '@'
      },
      link: function (scope, element, attr) {
        scope.textSize = scope.value;
        scope.$watch('textSize', function (size) {
          $document[0].body.style.fontSize = size + scope.unit;
        });
      }
    }
  }]);

以下是plunker链接:

https://plnkr.co/edit/uzggs7sVA5KCuuHxQ2Yh?p=preview

预期结果必须如下图所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以通过获取滑块的宽度并将其乘以当前值除以最大值来添加跨度,然后相对于范围滑块移动它。

angular.module('textSizeSlider', [])
  .directive('textSizeSlider', ['$document', function ($document) {

    var ctrl = ['$scope', '$element', function ($scope, $element) {
        $scope.position = 0;
        $scope.updatepointer = () => {
          var input =  $element.find("input");
          var width = input[0].offsetWidth -16; // 16 for offsetting padding
          var ratio = ($scope.textSize - $scope.min) / ($scope.max - $scope.min);
          var position = width * ratio;
          $scope.position = Math.trunc(position); 

        }

    }]

    return {
      controller: ctrl,
      restrict: 'E',
      template: '<div class="text-size-slider"><span class="pointer" style="left:{{position}}px;"><span>{{textSize}}</span></span><span class="small-letter" ng-style="{ fontSize: min + unit }">A</span> <input type="range" min="{{ min }}" max="{{ max }}" step="{{ step || 0 }}" ng-model="textSize" class="slider" value="{{ value }}" ng-change="updatepointer()" /> <span class="big-letter" ng-style="{ fontSize: max + unit }">A</span></div>',
      scope: {
        min: '@',
        max: '@',
        unit: '@',
        value: '@',
        step: '@'
      },
      link: function (scope, element, attr) {
        scope.textSize = scope.value;

        scope.$watch('textSize', function (size) {
          $document[0].body.style.fontSize = size + scope.unit;
          scope.updatepointer();
        });
      }
    }
  }]);

我在这里添加了指针的css:

.pointer {
  height: 40px;
  width: 40px;
  border-radius:20px 20px  0 20px;
  background-color:#FFF;
  display:block;
  transform: rotate(45deg);
  position:absolute;
  top: -44px;
  margin-left:8px;

}

.pointer span {
  display: inline-block;
  transform: rotate(-45deg);
  margin-left:12px;
  margin-top: 14px;


}

工作人员在这里:https://plnkr.co/edit/9bYR1aprS3Xn7YWyB6kj?p=preview