我有一个场景,因为我必须使用范围 slider 来调整字体大小,但是我有一个普通的 slider ,我需要在滑动时在工具提示上显示字体大小。
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
预期结果必须如下图所示:
最佳答案
您可以添加一个跨度,然后通过获取 slider 的宽度并将其乘以当前值除以最大值来相对于范围 slider 移动它。
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
关于javascript - 如何制作字体大小的自定义范围 slider ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43809251/