1685287258
another_xlider
(Flutter Slider) A material design slider and range slider, horizontal and vertical, with rtl support and lots of options and customizations for flutter
A single slider
FlutterSlider(
values: [300],
max: 500,
min: 0,
onDragging: (handlerIndex, lowerValue, upperValue) {
_lowerValue = lowerValue;
_upperValue = upperValue;
setState(() {});
},
)
To make slider Right To Left
use rtl: true
FlutterSlider(
...
rtl: true,
...
)
A simple example of range slider
FlutterSlider(
values: [30, 420],
rangeSlider: true,
max: 500,
min: 0,
onDragging: (handlerIndex, lowerValue, upperValue) {
_lowerValue = lowerValue;
_upperValue = upperValue;
setState(() {});
},
)
You can change the axis of your slider by setting axis
to Axis.vertical
. Default is horizontal
FlutterSlider(
...
axis: Axis.vertical,
...
)
You can customize handlers using handler
and rightHandler
properties.
Both handler
and rightHandler
accept FlutterSliderHandler
class which has following properties:
child
: is a widgetdisabled
: to disable the handlerdecoration
, foregroundDecoration
and transform
are come from Container()
widgetFlutterSlider(
...
handler: FlutterSliderHandler(
decoration: BoxDecoration(),
child: Material(
type: MaterialType.canvas,
color: Colors.orange,
elevation: 3,
child: Container(
padding: EdgeInsets.all(5),
child: Icon(Icons.adjust, size: 25,)),
),
),
rightHandler: FlutterSliderHandler(
child: Icon(Icons.chevron_left, color: Colors.red, size: 24,),
),
...
)
You can control the scale animation type of your handlers, it's duration and it's scale size using handlerAnimation
handlerAnimation
accepts a FlutterSliderHandlerAnimation
class which has 4 properties as following
FlutterSlider(
...
handlerAnimation: FlutterSliderHandlerAnimation(
curve: Curves.elasticOut,
reverseCurve: Curves.bounceIn,
duration: Duration(milliseconds: 500),
scale: 1.5
),
...
)
if you don't want scale animation, then just pass 1
to scale
property
if you don't want reverseCurve
, just ignore it. default is null
To customize track bars you can use FlutterSliderTrackBar
. You can see the details here
FlutterSlider(
...
trackBar: FlutterSliderTrackBar(
activeTrackBarHeight: 5,
),
...
)
inactiveTrackBarColor
and activeTrackBarColor
properties are removed. use inactiveTrackBar
and activeTrackBar
instead.
FlutterSlider(
...
trackBar: FlutterSliderTrackBar(
inactiveTrackBar: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.black12,
border: Border.all(width: 3, color: Colors.blue),
),
activeTrackBar: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: Colors.blue.withOpacity(0.5)
),
),
...
)
If you want to have a widget in the middle of your slider, you can use centralWidget
FlutterSlider(
...
trackBar: FlutterSliderTrackBar(
centralWidget: Container(
decoration: BoxDecoration(
color: trackBarColor,
borderRadius: BorderRadius.circular(50)
),
width: 9,
height: 9,
),
),
...
)
In order to customize your tooltips, you can use FlutterSliderTooltip
class. You can see all properties here
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
textStyle: TextStyle(fontSize: 17, color: Colors.white),
boxStyle: FlutterSliderTooltipBox(
decoration: BoxDecoration(
color: Colors.redAccent.withOpacity(0.7)
)
)
),
...
)
Here there is a range slider with customized handlers, trackbars and tooltips
You can use leftPrefix
, leftSuffix
, rightPrefix
, rightSuffix
to add your desired widget around tooltip content.
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
leftPrefix: Icon(Icons.attach_money, size: 19, color: Colors.black45,),
rightSuffix: Icon(Icons.attach_money, size: 19, color: Colors.black45,),
),
...
)
If you want to change the format of the value of tooltip you can use format
method.
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
format: (String value) {
return value + ' ! ';
}
),
...
)
If you want to fully change tooltip widget and use your own customized widget, you can use custom
function.
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
custom: (value) {
return Text(value.toString());
}
),
...
)
To disable tooltips, use disabled
in FlutterSliderTooltip
class
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
disabled: true,
),
...
)
To change the direction of the tooltip, you can use direction
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
direction: FlutterSliderTooltipDirection.right,
),
...
)
By default tooltip alignment is center, but you can modify it's top
, left
, right
and bottom
by using positionOffset
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
positionOffset: FlutterSliderTooltipPositionOffset(
top: -100
),
),
...
)
Tooltips always displayed if this property is set to true
.
FlutterSlider(
...
tooltip: FlutterSliderTooltip(
alwaysShowTooltip: true,
),
...
)
By default both handlers size are 35 width and height, but you can change this by handlerWidth
and handlerHeight
FlutterSlider(
...
handlerWidth: 30,
handlerHeight: 30,
...
)
You can tap on the slider to select it's value.
if slider is range-slider, then the closest handler to the selected point will move to that point
FlutterSlider(
...
selectByTap: true, // default is true
...
)
if you want to move your handlers by touching and moving active TrackBar, you have to set this to false
By default slider handlers move fluently, if you set jump
to true, handlers will jump between intervals
FlutterSlider(
...
jump: true,
...
)
The amount the slider changes on movement can be set using step
option
FlutterSlider(
...
step: FlutterSliderStep(step: 1),
...
)
If you want to have a non-linear slider with different steps, simply use rangeStep
feature.
FlutterSlider(
min: 0,
max: 1000000,
...
step: FlutterSliderStep(
step: 1, // default
isPercentRange: true, // ranges are percents, 0% to 20% and so on... . default is true
rangeList: [
FlutterSliderRangeStep(from: 0, to: 20, step: 10000),
FlutterSliderRangeStep(from: 20, to: 100, step: 200000),
]
),
...
)
If your configurations requires that some steps are not available, you can use ignoreSteps
property.
this property accepts a simple class to define from
and to
ranges.
FlutterSlider(
...
ignoreSteps: [
FlutterSliderIgnoreSteps(from: 8000, to: 12000),
FlutterSliderIgnoreSteps(from: 18000, to: 22000),
],
...
)
If you want to have an array of fixed items and slide through it, you can use fixedValues
property. use FlutterSliderFixedValue
to add your fixed values.FlutterSliderFixedValue
has following properties:
percent
: (int) ( between 0..100 inclusive). the position of fixed itemvalue
: (dynamic) the value of fixed itemfixedValues
, values of values
property, must be within 0..100FlutterSlider(
...
values: [ 10, 50 ],
fixedValues: [
FlutterSliderFixedValue(percent: 0, value: "1000"),
FlutterSliderFixedValue(percent: 10, value: "10K"),
FlutterSliderFixedValue(percent: 50, value: 50000),
FlutterSliderFixedValue(percent: 80, value: "80M"),
FlutterSliderFixedValue(percent: 100, value: "100B"),
],
...
)
using above example, you get (string) 10K
as upperValue
or lowerValue
(depends on handler), when you reach to 10 percent of the slider, you get (int) 50000
when you reach 50 percent of the slider and so on...
when using fixedValues
, min
and max
are ignored
When using range slider, the minimum distance between two handlers can be defined using minimumDistance
option
FlutterSlider(
...
minimumDistance: 300,
...
)
This is the opposite of minimum distance, when using range slider, the maximum distance between two handlers can be defined using maximumDistance
option
FlutterSlider(
...
maximumDistance: 300,
...
)
If you want to lock your handlers by a certain value, you can use lockHandlers
and lockDistance
properties
FlutterSlider(
...
lockHandlers: true,
lockDistance: 50,
...
)
You can display a Hatch Mark
underneath or beside of your slider based on axis
. In order to display hatch mark you must
use FlutterSliderHatchMark
class which has following properties:
linesDistanceFromTrackBar
: The distance of lines from slider. can be negative
bigLine
: The widget of big lines in hatch mark
smallLine
: The widget of small lines in hatch mark
linesAlignment
: the direct of lines, right
or left
which works as top
or bottom
on horizontal slider
density
: The number of lines per percent. 1 is default. any number less or more than 1 will decrease and increase lines respectively
smallDensity
: The number of small lines between any two big lines. 4 is default. any number less or more than 4 will decrease and increase lines respectively.
displayLines
: to display lines. by default is false
for the sake of optimization
labels
: If you want to display some label or text at certain percent in your hatch mark, you can use labels
labelBox
: The widget of label box, however, you can define a widget for each label and have it's own style
labelsDistanceFromTrackBar
: The distance of labels from slider. can be negative
disabled
: to disabled the whole hatchmark ( hide )
labels alignment is center
Here is an example:
FlutterSlider(
...
hatchMark: FlutterSliderHatchMark(
density: 0.5, // means 50 lines, from 0 to 100 percent
labels: [
FlutterSliderHatchMarkLabel(percent: 0, label: Text('Start')),
FlutterSliderHatchMarkLabel(percent: 10, label: Text('10,000')),
FlutterSliderHatchMarkLabel(percent: 50, label: Text('50 %')),
FlutterSliderHatchMarkLabel(percent: 80, label: Text('80,000')),
FlutterSliderHatchMarkLabel(percent: 100, label: Text('Finish')),
],
),
...
)
If you want the value of your slider originates from center of the slider, then you can use centeredOrigin
property
FlutterSlider(
...
centeredOrigin: true
...
...
trackBar: FlutterSliderTrackBar(
activeTrackBar: BoxDecoration(color: trackBarColor)
),
...
...
onDragging: (handlerIndex, lowerValue, upperValue) {
if (lowerValue > (max - min) / 2) {
trackBarColor = Colors.blueAccent;
} else {
trackBarColor = Colors.redAccent;
}
setState(() {});
})
...
)
You can control how big a handler's touch area could be. by default touch size is 25 The range is between 5 to 50
FlutterSlider(
...
touchSize: 25,
...
)
To see the touchable area for handlers, set visibleTouchArea
to true and test your slider
FlutterSlider(
...
visibleTouchArea: true,
...
)
to disable your slider, you can use disabled
.
FlutterSlider(
...
disabled: true,
...
)
makes the slider Right To Left
FlutterSlider(
...
rtl: true,
...
)
There are 3 events
onDragStarted
: fires when drag startsonDragCompleted
fires when drag endsonDragging
keeps firing when dragging
All three of above functions returns three values.
(int handlerIndex, dynamic lowerValue, dynamic upperValue)
First value is handlerIndex
, which determines the handler. 0 is Left Handler
and 1 refers to Right Handler
FlutterSlider(
...
onDragging: (handlerIndex, lowerValue, upperValue) {
_lowerValue = lowerValue;
_upperValue = upperValue;
if(handlerIndex == 0)
print(" Left handler ");
setState(() {});
},
...
)
Working with dates are simple and straightforward. just pass standard unix timestamp as values like so:
FlutterSlider(
...
values: [
new DateTime(2019,6,1,0,0,0).millisecondsSinceEpoch.toDouble(), // lower date : 2019-06-01
new DateTime(2019,9,1,0,0,0).millisecondsSinceEpoch.toDouble(), // upper date : 2019-09-01
],
min: new DateTime(2019,1,1,0,0,0).millisecondsSinceEpoch.toDouble(), // start date : 2019-01-01
max: new DateTime(2020,1,1,0,0,0).millisecondsSinceEpoch.toDouble(), // finish date : 2020-01-01
step: FlutterSliderStep(step: 86400), // 1 day
...
...
tooltip: FlutterSliderTooltip(
custom: (value) {
DateTime dtValue = DateTime.fromMillisecondsSinceEpoch(value.toInt());
String valueInTime = dtValue.year.toString() + '-' + dtValue.month.toString() + '-' + dtValue.day.toString();
return Text( valueInTime );
}
)
...
)
based on https://pub.dev/packages/flutter_xlider
Run this command:
With Flutter:
$ flutter pub add another_xlider
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
another_xlider: ^3.0.1
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:another_xlider/another_xlider.dart';
import 'package:another_xlider/models/handler.dart';
import 'package:another_xlider/models/handler_animation.dart';
import 'package:another_xlider/models/hatch_mark.dart';
import 'package:another_xlider/models/hatch_mark_label.dart';
import 'package:another_xlider/models/ignore_steps.dart';
import 'package:another_xlider/models/slider_step.dart';
import 'package:another_xlider/models/tooltip/tooltip.dart';
import 'package:another_xlider/models/trackbar.dart';
import 'package:another_xlider/widgets/sized_box.dart';
import 'package:flutter/material.dart';
import 'package:another_xlider/another_xlider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
//
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Xlider Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double _lowerValue = 50;
double _lv = 50.0;
double _uv = 250.0;
double _lv1 = 1000.0;
double _uv1 = 15000.0;
double _lv2 = 3000.0;
double _uv2 = 17000.0;
double _lv3 = 3000;
double _uv3 = 3500;
double _lv4 = 0;
double _uv4 = 2500;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title!),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
_singleSlider(),
_singleSlider(rtl: true),
_rangeSlider(),
_rangeSliderIgnoreSteps(),
_customHandler(),
_tooltipExample(),
_hatchMarkWithLabels(),
],
),
),
);
}
FlutterSliderHandler customHandler(IconData icon) {
return FlutterSliderHandler(
decoration: BoxDecoration(),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [BoxShadow(color: Colors.blue.withOpacity(0.3), spreadRadius: 0.05, blurRadius: 5, offset: Offset(0, 1))],
),
child: Container(
margin: EdgeInsets.all(5),
decoration: BoxDecoration(color: Colors.blue.withOpacity(0.3), shape: BoxShape.circle),
child: Icon(
icon,
color: Colors.white,
size: 23,
),
),
),
);
}
_singleSlider({bool rtl = false}) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text('Single Slider ' + (rtl ? 'RTL' : 'LTR')),
subtitle: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlutterSlider(
handlerWidth: 30,
rtl: rtl,
handlerHeight: 30,
values: [_lowerValue],
max: 100,
min: 0,
tooltip: FlutterSliderTooltip(
disabled: true,
),
trackBar: FlutterSliderTrackBar(activeTrackBar: BoxDecoration(color: Colors.blue.withOpacity(0.5))),
onDragging: (handlerIndex, lowerValue, upperValue) {
setState(() {
_lowerValue = lowerValue;
});
},
onDragCompleted: (handlerIndex, lowerValue, upperValue) {
setState(() {
_lowerValue = lowerValue;
});
},
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
child: Text(
_lowerValue.toInt().toString() + ' %',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
),
),
],
),
),
);
}
_rangeSlider() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text('Range Slider'),
subtitle: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlutterSlider(
values: [_lv, _uv],
rangeSlider: true,
max: 500,
min: 0,
onDragging: (_handlerIndex, _lowerValue, _upperValue) {
setState(() {
_lv = _lowerValue;
_uv = _upperValue;
});
},
)),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
child: Text(
_lv.toInt().toString() + ' - ' + _uv.toInt().toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
),
),
],
),
),
);
}
_rangeSliderIgnoreSteps() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text('Range Slider - Ignore Steps (8000 - 12000) and (18000 - 22000)'),
subtitle: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlutterSlider(
values: [_lv1, _uv1],
rangeSlider: true,
ignoreSteps: [
FlutterSliderIgnoreSteps(from: 8000, to: 12000),
FlutterSliderIgnoreSteps(from: 18000, to: 22000),
],
max: 25000,
min: 0,
step: FlutterSliderStep(step: 100),
jump: true,
trackBar: FlutterSliderTrackBar(
activeTrackBarHeight: 5,
),
tooltip: FlutterSliderTooltip(
textStyle: TextStyle(fontSize: 17, color: Colors.lightBlue),
),
handler: FlutterSliderHandler(
decoration: BoxDecoration(),
child: Material(
type: MaterialType.canvas,
color: Colors.orange,
elevation: 10,
child: Container(
padding: EdgeInsets.all(5),
child: Icon(
Icons.adjust,
size: 25,
)),
),
),
rightHandler: FlutterSliderHandler(
child: Icon(
Icons.chevron_left,
color: Colors.red,
size: 24,
),
),
onDragging: (_handlerIndex, _lowerValue, _upperValue) {
setState(() {
_lv1 = _lowerValue;
_uv1 = _upperValue;
});
},
)),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
child: Text(
_lv1.toInt().toString() + ' - ' + _uv1.toInt().toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
),
),
],
),
),
);
}
_customHandler() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text('Range Slider - Custom Handler'),
subtitle: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlutterSlider(
values: [_lv2, _uv2],
rangeSlider: true,
max: 25000,
min: 0,
step: FlutterSliderStep(step: 100),
jump: true,
trackBar: FlutterSliderTrackBar(
inactiveTrackBarHeight: 2,
activeTrackBarHeight: 3,
),
disabled: false,
handler: customHandler(Icons.chevron_right),
rightHandler: customHandler(Icons.chevron_left),
tooltip: FlutterSliderTooltip(
leftPrefix: Icon(
Icons.attach_money,
size: 19,
color: Colors.black45,
),
rightSuffix: Icon(
Icons.attach_money,
size: 19,
color: Colors.black45,
),
textStyle: TextStyle(fontSize: 17, color: Colors.black45),
),
onDragging: (_handlerIndex, _lowerValue, _upperValue) {
setState(() {
_lv2 = _lowerValue;
_uv2 = _upperValue;
});
},
)),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
child: Text(
_lv2.toInt().toString() + ' - ' + _uv2.toInt().toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
),
),
],
),
),
);
}
_tooltipExample() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text('Range Slider - tooltip example'),
subtitle: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlutterSlider(
key: Key('3343'),
values: [_lv3, _uv3],
rangeSlider: true,
tooltip: FlutterSliderTooltip(
alwaysShowTooltip: true,
),
max: 4000,
min: 0,
step: FlutterSliderStep(step: 20),
jump: true,
onDragging: (_handlerIndex, _lowerValue, _upperValue) {
setState(() {
_lv3 = _lowerValue;
_uv3 = _upperValue;
});
},
)),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
child: Text(
_lv3.toInt().toString() + ' - ' + _uv3.toInt().toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
),
),
],
),
),
);
}
_hatchMarkWithLabels() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text('Range Slider - Hatch Mark with labels'),
subtitle: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlutterSlider(
key: Key('3343'),
values: [_lv4, _uv4],
touchSize: 50.0,
handlerAnimation: FlutterSliderHandlerAnimation(reverseCurve: Curves.bounceOut, curve: Curves.bounceIn, duration: Duration(milliseconds: 500), scale: 1.5),
rangeSlider: true,
ignoreSteps: [
FlutterSliderIgnoreSteps(from: 500, to: 1000),
],
hatchMark: FlutterSliderHatchMark(
displayLines: true,
linesDistanceFromTrackBar: 10,
labelBox: FlutterSliderSizedBox(
width: 40,
height: 20,
foregroundDecoration: BoxDecoration(color: Color.fromARGB(39, 54, 165, 244)),
transform: Matrix4.translationValues(0, 30, 0),
),
density: 0.5,
labels: [
FlutterSliderHatchMarkLabel(percent: 0, label: Text('Start')),
FlutterSliderHatchMarkLabel(percent: 20, label: Text('N/A')),
FlutterSliderHatchMarkLabel(percent: 10, label: Text('10 %')),
FlutterSliderHatchMarkLabel(percent: 50, label: Text('50 %')),
FlutterSliderHatchMarkLabel(percent: 80, label: Text('80 %')),
FlutterSliderHatchMarkLabel(percent: 100, label: Text('Finish')),
],
),
rightHandler: FlutterSliderHandler(
decoration: BoxDecoration(),
child: Container(
decoration: BoxDecoration(
color: Colors.blue,
shape: BoxShape.circle,
),
),
),
tooltip: FlutterSliderTooltip(
alwaysShowTooltip: false,
),
max: 4000,
min: 0,
step: FlutterSliderStep(step: 100),
jump: true,
onDragging: (_handlerIndex, _lowerValue, _upperValue) {
setState(() {
_lv4 = _lowerValue;
_uv4 = _upperValue;
});
},
)),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
child: Text(
_lv4.toInt().toString() + ' - ' + _uv4.toInt().toString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
),
),
],
),
),
);
}
}
Download Details:
Author: daniscript.com
Source Code: https://github.com/loonix/another_xlider
1684938420
Слайдеры изображений в React — это обычная функция на многих веб-сайтах, и они могут помочь продемонстрировать различные изображения или продукты в визуально привлекательной форме.
В этом руководстве мы покажем вам, как создать слайдер изображений в React JS с помощью популярного пакета react-slick. Чтобы создать слайдер изображения в React JS, вам обычно нужно установить пакет слайдера, импортировать пакет в свой компонент, определить настройки слайдера и содержимое слайда, а также добавить компонент слайдера в свое приложение.
С помощью этих шагов вы можете легко добавить слайдер изображений в свое приложение React и улучшить его визуальную привлекательность и функциональность.
Прежде чем мы начнем создавать слайдер изображений в React , убедитесь, что у вас установлено следующее:
Если у вас не установлен React JS, вы можете установить его на свой компьютер, следуя официальной документации.
Первый шаг — установить пакет react-slick. Вы можете сделать это с помощью npm или yarn, выполнив следующую команду в своем терминале:
npm install react-slick
Затем вам нужно импортировать react-slick в ваш компонент React, чтобы создать слайдер изображений в React . Вы можете сделать это, добавив следующий код вверху файла:
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
Теперь пришло время создать компонент слайдера изображений . Вы можете сделать это, добавив следующий код в свой компонент:
const ImageSlider = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000
};
return (
<Slider {...settings}>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 1" data-lazy-src="image1.jpg" /><noscript><img decoding="async" src="image1.jpg" alt="Image 1" /></noscript>
</div>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 2" data-lazy-src="image2.jpg" /><noscript><img decoding="async" src="image2.jpg" alt="Image 2" /></noscript>
</div>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 3" data-lazy-src="image3.jpg" /><noscript><img decoding="async" src="image3.jpg" alt="Image 3" /></noscript>
</div>
</Slider>
);
};
В этом коде мы определяем ImageSliderкомпонент, который содержит Sliderкомпонент из пакета react-slick. Мы также определяем некоторые настройки для ползунка, такие как количество слайдов для одновременного отображения, скорость анимации и необходимость автоматического воспроизведения ползунка.
Внутри Sliderкомпонента мы определяем три divэлемента, каждый из которых содержит imgтег с URL-адресом изображения и альтернативный текст.
Наконец, вам нужно добавить ImageSliderкомпонент в ваше приложение. Вы можете сделать это, просто визуализировав компонент в своем приложении:
function App() {
return (
<div className="App">
<ImageSlider />
</div>
);
}
Функция Appвозвращает элемент JSX, который представляет собой расширение синтаксиса для JavaScript, позволяющее вам писать HTML-подобный код в ваших файлах JavaScript.
В этом случае код JSX определяет divэлемент с именем класса «Приложение», который содержит ImageSliderкомпонент.
Заключение
В этом руководстве мы показали вам, как создать слайдер изображений в React JS с помощью пакета react-slick. Выполнив эти шаги, вы должны получить полнофункциональный слайдер изображений в своем приложении React.
Вы можете настроить ползунок изображений React и добавить дополнительные изображения по мере необходимости, чтобы ползунок работал для вашего конкретного случая использования.
Оригинальный источник статьи: https://foolishdeveloper.com/
1684934609
React 中的图像滑块 是许多网站的常见功能,它们可以帮助以视觉上吸引人的方式展示不同的图像或产品。
在本教程中,我们将向您展示如何使用流行的 react-slick 包在 React JS 中创建图像滑块。要在 React JS 中创建图像滑块,您通常需要安装滑块包,将包导入您的组件,定义滑块设置和幻灯片内容,并将滑块组件添加到您的应用程序。
通过这些步骤,您可以轻松地将图像滑块添加到您的 React应用程序并增强其视觉吸引力和功能。
在我们开始在 React 中创建 Image Slider 之前,请确保您已安装以下内容:
如果你没有安装 React JS,你可以按照官方文档在你的机器上安装它。
第一步是安装 react-slick 包。您可以使用 npm 或 yarn 通过在终端中运行以下命令来执行此操作:
npm install react-slick
接下来,您需要在 React 组件中导入 react-slick 以在 React 中创建一个 Image Slider。您可以通过在文件顶部添加以下代码来执行此操作:
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
现在是创建图像滑块组件的时候了。您可以通过将以下代码添加到您的组件来执行此操作:
const ImageSlider = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000
};
return (
<Slider {...settings}>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 1" data-lazy-src="image1.jpg" /><noscript><img decoding="async" src="image1.jpg" alt="Image 1" /></noscript>
</div>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 2" data-lazy-src="image2.jpg" /><noscript><img decoding="async" src="image2.jpg" alt="Image 2" /></noscript>
</div>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 3" data-lazy-src="image3.jpg" /><noscript><img decoding="async" src="image3.jpg" alt="Image 3" /></noscript>
</div>
</Slider>
);
};
在此代码中,我们定义了ImageSlider组件,其中包含Slider来自 react-slick 包的组件。我们还为滑块定义了一些设置,例如一次显示的幻灯片数量、动画速度以及是否自动播放滑块。
在组件内部Slider,我们定义了三个div元素,每个元素都包含一个img带有图像 URL 的标签和一个替代文本。
最后,您需要将ImageSlider组件添加到您的应用程序中。您可以通过简单地在您的应用程序中渲染组件来做到这一点:
function App() {
return (
<div className="App">
<ImageSlider />
</div>
);
}
该App函数返回一个 JSX 元素,它是 JavaScript 的语法扩展,允许您在 JavaScript 文件中编写类似 HTML 的代码。
在这种情况下,JSX 代码定义了一个div类名为“App”的元素,其中包含一个ImageSlider组件。
结论
在本教程中,我们向您展示了如何使用 react-slick 包在 React JS 中创建图像滑块。通过执行这些步骤,您现在应该在您的 React 应用程序中拥有一个功能齐全的图像滑块。
您可以自定义React 图像滑块并根据需要添加更多图像,以使滑块适用于您的特定用例。
文章原文出处:https: //foolishdeveloper.com/
1684927200
Image sliders in React are a common feature in many websites, and they can help showcase different images or products in a visually appealing way.
In this tutorial, we’ll show you how to create an image slider in React JS using the popular react-slick package. To create an image slider in React JS, you’ll typically need to install a slider package, import the package in your component, define the slider settings and slide content, and add the slider component to your app.
With these steps, you can easily add an image slider to your React app and enhance its visual appeal and functionality.
Before we begin to create Image Slider in React, make sure you have the following installed:
If you don’t have React JS installed, you can follow the official documentation to install it on your machine.
The first step is to install the react-slick package. You can do this using npm or yarn by running the following command in your terminal:
npm install react-slick
Next, you need to import react-slick in your React component to create an Image Slider in React. You can do this by adding the following code at the top of your file:
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
Now it’s time to create the image slider component. You can do this by adding the following code to your component:
const ImageSlider = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000
};
return (
<Slider {...settings}>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 1" data-lazy-src="image1.jpg" /><noscript><img decoding="async" src="image1.jpg" alt="Image 1" /></noscript>
</div>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 2" data-lazy-src="image2.jpg" /><noscript><img decoding="async" src="image2.jpg" alt="Image 2" /></noscript>
</div>
<div>
<img decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E" alt="Image 3" data-lazy-src="image3.jpg" /><noscript><img decoding="async" src="image3.jpg" alt="Image 3" /></noscript>
</div>
</Slider>
);
};
In this code, we’re defining the ImageSlider
component, which contains the Slider
component from the react-slick package. We’re also defining some settings for the slider, such as the number of slides to show at once, the speed of the animation, and whether or not to autoplay the slider.
Inside the Slider
component, we’re defining three div
elements, each containing an img
tag with the URL of the image and an alt text.
Finally, you need to add the ImageSlider
component to your app. You can do this by simply rendering the component in your app:
function App() {
return (
<div className="App">
<ImageSlider />
</div>
);
}
The App
function returns a JSX element, which is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files.
In this case, the JSX code defines a div
element with a class name of “App” that contains an ImageSlider
component.
Conclusion
In this tutorial, we showed you how to create an image slider in React JS using the react-slick package. By following these steps, you should now have a fully functional image slider in your React app.
You can customize the React image slider and add more images as needed to make the slider work for your specific use case.
Original article source at: https://foolishdeveloper.com/
1684470120
В этой статье я покажу, как использовать современные методы CSS для создания привлекательного пользовательского слайдера диапазона, используя только собственный HTML- <input>элемент.
Ползунки диапазона ( <input type="range">) позволяют пользователям выбирать значение в заданном диапазоне, предоставляя альтернативные типы ввода, такие как <input type="number">.
Стили ползунка диапазона по умолчанию выглядят не очень хорошо. Изображение ниже дает представление о том, как диапазон ползунков, которые мы будем стилизовать, отображаются по умолчанию в Chrome, Firefox и Safari.
Но <input>элементы трудно стилизовать. Большинство онлайн-решений для их стилизации основаны на JavaScript и каком-то загроможденном коде. Что еще хуже, некоторые из этих методов также нарушают доступность элемента.
Итак, давайте посмотрим, как сделать что-то лучше, используя только CSS и не ставя под угрозу доступность. Демонстрация CodePen ниже показывает, что мы будем создавать.
Круто, да? Вы также найдете варианты этих стилей в конце статьи!
Начнем с разбора структуры элемента ввода диапазона. Это нативный элемент, и каждый браузер имеет собственную реализацию таких элементов. В основном у нас есть две разные реализации.
Есть один для браузеров Webkit и Blink, таких как Chrome, Edge, Safari и Opera:
<input type="range" min="0" max="100" step="1" value="20">
<div>
<div pseudo="-webkit-slider-runnable-track" id="track">
<div id="thumb">
</div>
</div>
</div>
</input>
А это для Firefox:
<input type="range" min="0" max="100" step="1" value="20">
<div></div>
<div></div>
<div></div>
</input>
Есть и третья реализация для IE, но, к счастью, этот браузер уже почти мертв!
Такое несоответствие между браузерами усложняет задачу, поскольку нам нужно обеспечить разные стили для каждой реализации. Я не буду углубляться в это, так как статья никогда не закончится, но я настоятельно рекомендую прочитать эту статью Аны Тюдор для более глубокого изучения.
Единственное, что вам нужно иметь в виду, это то, что, какой бы ни была реализация, у нас всегда есть «большой палец» как общий компонент.
Я собираюсь только стилизовать этот элемент, что упростит настройку моего пользовательского ползунка диапазона. Давайте сразу перейдем к коду, чтобы увидеть магию в игре.
Первый шаг — сбросить и отключить все стили браузера по умолчанию, используя appearance: noneи некоторые другие общие свойства:
input {
appearance :none;
background: none;
cursor: pointer;
}
В более сложном сценарии нам может потребоваться добавить дополнительный код, если к нашему элементу применяются другие стили по умолчанию. Просто нужно убедиться, что у нас есть «голый» элемент без каких-либо визуальных стилей.
Давайте также определим несколько переменных CSS, чтобы мы могли легко создавать различные варианты для ползунка диапазона. Не волнуйтесь, если какой-то из приведенных ниже кодов покажется вам сложным. Нам просто нужно обновить несколько переменных, чтобы управлять нашим ползунком:
input {
--c: orange; /* active color */
--g: 8px; /* the gap */
--l: 5px; /* line thickness*/
--s: 30px; /* thumb size*/
width: 400px; /* input width */
height: var(--s);
appearance :none;
background: none;
cursor: pointer;
}
На этом этапе виден только значок большого пальца со стилями по умолчанию, как показано в приведенной ниже демонстрации CodePen.
Давайте стилизуем элемент большого пальца. Начнем с базовой настройки:
<thumb selector> {
height: var(--s);
aspect-ratio: 1;
border-radius: 50%;
box-shadow: 0 0 0 var(--l) inset var(--c);
appearance: none;
}
Код должен быть понятным. Пока ничего особенного, и мы получим результат, показанный ниже.
Обратите внимание на использование двух разных селекторов, как мы объясняли в первом разделе:
/* Chrome, Edge, Safari, Opera */
input[type="range" i]::-webkit-slider-thumb { }
/* Firefox */
input[type="range"]::-moz-range-thumb { }
Но как узнать, какой селектор использовать?
Я просто проверил код ввода с помощью инструментов разработчика браузера, чтобы увидеть селектор, который каждый браузер использует для стилизации большого пальца. В статье, которой я поделился ранее, показано, как манипулировать инструментами разработчика для получения такой информации.
Теперь мы собираемся использовать волшебный прием CSS, чтобы завершить наш слайдер. Она предполагает использование border-image:
border-image: linear-gradient(90deg,var(--_c) 50%,#ababab 0) 1/0 100vw/0 calc(100vw + var(--g));
Я знаю, это выглядит пугающе, но давайте проанализируем эту линию, и вы увидите, что это не так сложно. Вышеприведенное является сокращением для следующего:
border-image-source: linear-gradient(90deg,var(--c) 50%,#ababab 0);
border-image-slice: 1;
border-image-width: 0 100vw;
border-image-outset: 0 calc(100vw + var(--g));
Со страницы MDN читаем:
Свойство border-imageCSS рисует изображение вокруг заданного элемента. Он заменяет обычную границу элемента.
Наше изображение будет градиентом двух цветов — основного (определяемого --c) и серого цвета. Нам нужно, чтобы изображение границы покрывало все пространство ввода по горизонтали, поэтому мы используем большое значение ширины слева и справа ( 100vw), а верх и низ оставляем равными ( 0).
Но border-image-widthограничен размером элемента. Чтобы преодолеть это, нам нужно также использовать большое значение для border-image-outsetувеличения пространства, доступного для изображения границы. Снова из MDN :
Свойство border-image-outsetCSS задает расстояние, на которое изображение границы элемента отстоит от его рамки.
Части граничного изображения, отображаемые за пределами рамки элемента с помощью , border-image-outsetне запускают полосы прокрутки переполнения и не фиксируют события мыши.
Когда вы впервые видите ползунок, кажется, что мы увеличиваем основной цвет слева, но на самом деле мы скользим по фиксированному градиенту, который переполняет наш элемент.
Следующая демонстрация дает обзор того, что происходит под капотом.
Перетащите большой палец и сдвиньте его, чтобы увидеть, как все движется. Я использую небольшое значение для ширины и начала, чтобы мы могли легко понять трюк.
Также обратите внимание, что начало должно быть больше, чем ширина, чтобы был зазор. По этой причине он определяется равным ширине плюс значение зазора.
При добавлении overflow: hiddenк элементу ввода и использовании большого значения иллюзия становится идеальной, как показано ниже.
Что насчет border-image-slice? Почему значение 1?
Это свойство немного сложное, но обязательное при использовании border-image. В нашем случае это значение не очень актуально, и небольшое положительное значение будет работать. У меня есть подробный ответ на переполнение стека , если вы хотите узнать об этом больше.
Последний шаг — уменьшить размер полосы, чтобы он соответствовал размеру, который мы определили с помощью переменной --l. Для этого мы будем использовать clip-path:
clip-path:
polygon(
0 calc(50% + var(--l)/2),
-100vw calc(50% + var(--l)/2),
-100vw calc(50% - var(--l)/2),
0 calc(50% - var(--l)/2),
0 0,100% 0,
100% calc(50% - var(--l)/2),
100vw calc(50% - var(--l)/2),
100vw calc(50% + var(--l)/2),
100% calc(50% + var(--l)/2),
100% 100%,0 100%);
На изображении ниже представлен обзор различных точек для понимания формы многоугольника.
Вот и все! У нас есть собственный ползунок диапазона с несколькими строками кода, которым вы можете легко управлять, настраивая несколько переменных.
А как насчет тонкой анимации, когда мы взаимодействуем с ползунком? Для этого не нужно много кода, и это улучшит UX слайдера.
Во-первых, мы собираемся преобразовать большой палец из круга только с рамкой в полный круг, когда мы щелкнем по нему. Для этого мы увеличиваем значение спреда box-shadow. Помните, что мы использовали box-shadowдля определения границы большого пальца:
box-shadow: 0 0 0 var(--l) inset var(--c);
Мы обновляем var(--l)с var(--s)помощью :activeселектора и файла :focus-visible. Последнее связано с навигацией с помощью клавиатуры и позволяет нам добиться одинакового эффекта независимо от того, используем ли мы мышь или клавиатуру.
Код выглядит следующим образом:
input[type="range" i]::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
transition: .3s;
}
input[type="range" i]::-moz-range-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
transition: .3s;
}
input:active::-webkit-slider-thumb,
input:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
}
input:active::-moz-range-thumb,
input:focus-visible::-moz-range-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
}
Это немного долго для box-shadowперехода, не так ли? Мы можем оптимизировать его с помощью переменной CSS:
input[type="range" i]::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--_b,var(--s)) inset var(--c);
transition: .3s;
}
input[type="range" i]::-moz-range-thumb {
box-shadow: 0 0 0 var(--_b,var(--s)) inset var(--c);
transition: .3s;
}
input:active,
input:focus-visible {
--_b: var(--s);
}
Я выражаю значение спреда с помощью переменной и просто обновляю эту переменную в :activeи :focus-visible.
Я также собираюсь добавить немного анимации к цвету. Я сделаю его немного темнее на :hover. Для этого я не буду обновлять цвет, а смешаю его с черным с помощью новой color-mix()функции. Этот трюк позволяет нам использовать основной цвет, определенный с помощью, --cа не определять новый темный цвет для каждого ползунка вручную:
--_c: color-mix(in srgb, var(--c), #000 var(--p,0%));
Я определяю новую переменную, которая заменит --cв коде. Затем, регулируя процент черного цвета ( #000) с помощью переменной --p, я контролирую «темноту» цвета:
input:focus-visible,
input:hover{
--p: 25%;
}
Эта функция поддерживается не во всех браузерах, поэтому настоятельно рекомендуется использовать запасной вариант:
@supports not (color: color-mix(in srgb,red,red)) {
input {
--_c: var(--c); /* if no support we keep the color as defined */
}
}
Наш ползунок диапазона теперь идеален!
Мы достигли конца, и нам не пришлось иметь дело со сложной реализацией, связанной с браузером! Мы идентифицировали селектор элемента thumb и, используя несколько приемов CSS, применили к нему стиль всего ползунка диапазона. Не будем забывать, что мы сделали это, используя только <input>элемент, поэтому нам не нужно беспокоиться о каких-либо проблемах доступности, поскольку мы сохранили нативную функциональность. Слайдер без проблем поддерживает навигацию с помощью клавиатуры.
Вот еще примеры слайдеров, использующих ту же технику. Я позволю вам проанализировать их код в качестве упражнения.
Оригинальный источник статьи: https://www.sitepoint.com/
1684466348
在本文中,我将展示如何使用现代 CSS 技术创建一个引人注目的自定义范围滑块,只使用本机 HTML<input>元素。
范围滑块 ( <input type="range">) 让用户在给定范围内选择一个值,提供替代输入类型,例如<input type="number">。
默认范围滑块样式看起来不太好。下图展示了我们将设置样式的滑块在 Chrome、Firefox 和 Safari 中默认显示的范围。
但是<input>元素很难设计。大多数用于样式化它们的在线解决方案都依赖于 JavaScript 和一些混乱的代码。更糟糕的是,其中一些技术还破坏了元素的可访问性。
因此,让我们看看如何在不影响可访问性的情况下仅使用 CSS 来做得更好。下面的 CodePen 演示展示了我们将要构建的内容。
酷吧?您还会在本文末尾找到这些样式的变体!
让我们从剖析范围输入元素的结构开始。它是一个原生元素,每个浏览器都有自己的此类元素实现。我们主要有两种不同的实现。
有一个用于 Webkit 和 Blink 浏览器,例如 Chrome、Edge、Safari 和 Opera:
<input type="range" min="0" max="100" step="1" value="20">
<div>
<div pseudo="-webkit-slider-runnable-track" id="track">
<div id="thumb">
</div>
</div>
</div>
</input>
这是 Firefox 的:
<input type="range" min="0" max="100" step="1" value="20">
<div></div>
<div></div>
<div></div>
</input>
IE 有第三个实现,但谢天谢地,该浏览器现在几乎已经死了!
浏览器之间的这种不一致使任务变得困难,因为我们需要为每个实现提供不同的样式。我不会深入探讨这一点,因为文章永远不会结束,但我强烈建议阅读Ana Tudor 的这篇文章以进行更深入的探索。
您唯一需要记住的是,无论实现方式如何,我们始终将“拇指”作为通用组件。
我只会设计这个元素的样式,这将使我的自定义范围滑块易于自定义。让我们直接进入代码,看看其中的魔法。
第一步是通过使用appearance: none和其他一些常用属性来重置和禁用所有浏览器默认样式:
input {
appearance :none;
background: none;
cursor: pointer;
}
在更复杂的情况下,我们可能需要添加更多代码以防其他默认样式应用于我们的元素。只需要确保我们有一个没有任何视觉样式的“裸”元素。
我们还定义了一些 CSS 变量,以便我们可以轻松地为范围滑块创建不同的变体。如果下面的某些代码看起来很复杂,请不要担心。我们只需要更新几个变量来控制我们的滑块:
input {
--c: orange; /* active color */
--g: 8px; /* the gap */
--l: 5px; /* line thickness*/
--s: 30px; /* thumb size*/
width: 400px; /* input width */
height: var(--s);
appearance :none;
background: none;
cursor: pointer;
}
在此步骤中,只有缩略图的默认样式可见,如下面的 CodePen 演示所示。
让我们设置拇指元素的样式。我们将从基本设置开始:
<thumb selector> {
height: var(--s);
aspect-ratio: 1;
border-radius: 50%;
box-shadow: 0 0 0 var(--l) inset var(--c);
appearance: none;
}
代码应该是不言自明的。到目前为止没有什么特别的,我们将得到如下所示的结果。
请注意两个不同选择器的使用,正如我们在第一部分中解释的那样:
/* Chrome, Edge, Safari, Opera */
input[type="range" i]::-webkit-slider-thumb { }
/* Firefox */
input[type="range"]::-moz-range-thumb { }
但是你怎么知道要使用的选择器呢?
我只是使用浏览器的开发人员工具检查了输入代码,以查看每个浏览器用来设置缩略图样式的选择器。我之前分享的文章向您展示了如何操纵开发人员工具来获取此类信息。
现在我们将使用神奇的 CSS 技巧来完成我们的滑块。它涉及使用border-image:
border-image: linear-gradient(90deg,var(--_c) 50%,#ababab 0) 1/0 100vw/0 calc(100vw + var(--g));
我知道它看起来很可怕,但让我们剖析那条线,你会发现它并不那么困难。以上是以下内容的简写:
border-image-source: linear-gradient(90deg,var(--c) 50%,#ababab 0);
border-image-slice: 1;
border-image-width: 0 100vw;
border-image-outset: 0 calc(100vw + var(--g));
从MDN 页面,我们读到:
CSS属性border-image在给定元素周围绘制图像。它取代了元素的常规边框。
我们的图像将是具有两种颜色的渐变 - 主要颜色(由 定义--c)和灰色。我们需要边框图像水平覆盖输入的整个空间,因此我们使用较大的左右宽度值 ( 100vw),同时我们将顶部和底部保持在 ( 0)。
但是border-image-width受限于元素大小。为了克服这个问题,我们还需要使用一个大的值来border-image-outset增加边框图像的可用空间。再次来自MDN :
CSSborder-image-outset属性设置元素的边框图像与其边框框之间的距离。
在元素边框框外呈现的边框图像部分border-image-outset不会触发溢出滚动条,也不会捕获鼠标事件。
当您第一次看到滑块时,看起来我们正在增加左侧的主颜色,但实际上我们正在滑动一个溢出我们元素的固定渐变。
以下演示概述了幕后发生的事情。
拖动拇指并滑动它以查看事物的移动方式。我为宽度和开始使用了一个小值,这样我们就可以很容易地理解这个技巧。
另外,请注意,开始需要大于宽度才能有间隙。因此,它被定义为等于宽度加上间隙的值。
通过添加overflow: hidden到输入元素并使用大值,错觉是完美的,如下所示。
那呢border-image-slice?为什么值1?
这个属性有点棘手,但在使用border-image. 在我们的例子中,这个值不是很相关,一个小的正值就可以完成这项工作。如果您想了解更多信息,我有一个详细的Stack Overflow 答案。
最后一步是减小条形的大小以匹配我们通过变量定义的大小--l。为此,我们将使用clip-path:
clip-path:
polygon(
0 calc(50% + var(--l)/2),
-100vw calc(50% + var(--l)/2),
-100vw calc(50% - var(--l)/2),
0 calc(50% - var(--l)/2),
0 0,100% 0,
100% calc(50% - var(--l)/2),
100vw calc(50% - var(--l)/2),
100vw calc(50% + var(--l)/2),
100% calc(50% + var(--l)/2),
100% 100%,0 100%);
下图提供了不同点的概览,以了解多边形的形状。
就是这样!我们有一个带有几行代码的自定义范围滑块,您可以通过调整几个变量轻松控制它。
当我们与滑块交互时,一些微妙的动画怎么样?它不需要很多代码,而且会增强滑块的用户体验。
首先,当我们点击它时,我们将把拇指从一个只有边框的圆圈变成一个完整的圆圈。为此,我们增加了box-shadow. 请记住,我们曾经box-shadow定义过拇指的边界:
box-shadow: 0 0 0 var(--l) inset var(--c);
我们var(--l)使用var(--s)选择:active器和:focus-visible. 后者与键盘导航有关,使我们无论使用鼠标还是键盘都具有相同的效果。
代码如下:
input[type="range" i]::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
transition: .3s;
}
input[type="range" i]::-moz-range-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
transition: .3s;
}
input:active::-webkit-slider-thumb,
input:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
}
input:active::-moz-range-thumb,
input:focus-visible::-moz-range-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
}
过渡有点冗长box-shadow,对吧?我们可以使用 CSS 变量对其进行优化:
input[type="range" i]::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--_b,var(--s)) inset var(--c);
transition: .3s;
}
input[type="range" i]::-moz-range-thumb {
box-shadow: 0 0 0 var(--_b,var(--s)) inset var(--c);
transition: .3s;
}
input:active,
input:focus-visible {
--_b: var(--s);
}
我使用一个变量表示价差值,我只是在:active和上更新该变量:focus-visible。
我还将为颜色添加一点动画。我会把它调暗一点:hover。为此,我不会更新颜色,而是使用新color-mix()函数将其与黑色混合。这个技巧允许我们使用由定义的主颜色,--c而不是手动为每个滑块定义新的深色:
--_c: color-mix(in srgb, var(--c), #000 var(--p,0%));
我正在定义一个新变量,它将替换--c代码中的 。#000然后通过使用变量调整黑色 ( ) 的百分比--p,我控制了颜色的“暗度”:
input:focus-visible,
input:hover{
--p: 25%;
}
并非每个浏览器都支持此功能,因此强烈建议使用回退:
@supports not (color: color-mix(in srgb,red,red)) {
input {
--_c: var(--c); /* if no support we keep the color as defined */
}
}
我们的范围滑块现在完美了!
我们已经走到了尽头,不必处理任何与浏览器相关的复杂实现!我们确定了 thumb 元素的选择器,并使用一些 CSS 技巧,用它设置了整个范围滑块的样式。别忘了我们只使用<input>元素来完成此操作,因此我们不必担心任何可访问性问题,因为我们保留了本机功能。滑块支持键盘导航没有问题。
以下是使用相同技术的滑块的更多示例。作为练习,我会让你剖析他们的代码。
文章原文出处:https: //www.sitepoint.com/
1684462447
In this article, I’ll show how to use modern CSS techniques to create an eye-catching, custom range slider with nothing but the native HTML <input>
element.
Range sliders (<input type="range">
) let users choose a value within a given range, providing an alternative input types such as <input type="number">
.
The default range slider styles don’t look great. The image below gives an idea of how range the sliders we’ll be styling are displayed by default in Chrome, Firefox and Safari.
But <input>
elements are hard to style. Most of the online solutions for styling them rely on JavaScript and some cluttered code. Worse still, some of these techniques also break the accessibility of the element.
So let’s look at how to do things better, using just CSS, and without compromising accessibility. The CodePen demo below shows what we’ll be building.
Cool right? You’ll also find variations on these styles at the end of the article!
Let’s start by dissecting the structure of the range input element. It’s a native element, and each browser has its own implementation of such elements. We mainly have two different implementations.
There’s one for Webkit and Blink browsers such as Chrome, Edge, Safari, and Opera:
<input type="range" min="0" max="100" step="1" value="20">
<div>
<div pseudo="-webkit-slider-runnable-track" id="track">
<div id="thumb">
</div>
</div>
</div>
</input>
And this is the one for Firefox:
<input type="range" min="0" max="100" step="1" value="20">
<div></div>
<div></div>
<div></div>
</input>
There’s a third implementation for IE, but thankfully that browser is all but dead and gone now!
Such inconsistency between browsers is what makes the task difficult, as we need to provide different styling for each implementation. I won’t dig more into this, as the article would never end, but I highly recommend reading this article by Ana Tudor for more in-depth exploration.
The only thing you need to keep in mind is that, whatever the implementation, we always have the “thumb” as a common component.
I’m only going to style this element, which will make my custom range slider easy to customize. Let’s jump straight into the code to see the magic in play.
The first step is to reset and disable all the browser default styles by using appearance: none
and some other common properties:
input {
appearance :none;
background: none;
cursor: pointer;
}
In a more complicated scenario, we may need to add more code in case other default styles are applied to our element. Simply just need to make sure we have a “naked” element without any visual styling.
Let’s also define a few CSS variables so we can easily create different variations for the range slider. Don’t worry if some of the code below looks complex. We just have to update a few variables to control our slider:
input {
--c: orange; /* active color */
--g: 8px; /* the gap */
--l: 5px; /* line thickness*/
--s: 30px; /* thumb size*/
width: 400px; /* input width */
height: var(--s);
appearance :none;
background: none;
cursor: pointer;
}
At this step, only the thumb is visible with its default styles, as the CodePen demo below shows.
Let’s style the thumb element. We’ll start with the basic setup:
<thumb selector> {
height: var(--s);
aspect-ratio: 1;
border-radius: 50%;
box-shadow: 0 0 0 var(--l) inset var(--c);
appearance: none;
}
The code should be self-explanatory. Nothing fancy so far, and we’ll get the result shown below.
Note the use of two different selectors, as we explained in the first section:
/* Chrome, Edge, Safari, Opera */
input[type="range" i]::-webkit-slider-thumb { }
/* Firefox */
input[type="range"]::-moz-range-thumb { }
But how do you know the selector to use?
I’ve simply inspected the code of the input using the browser’s developer tools to see the selector each browser is using to style the thumb. The article I shared previously shows you how to manipulate the developer tools to get such information.
Now we’re going to use a magic CSS trick to complete our slider. It involves the use of border-image
:
border-image: linear-gradient(90deg,var(--_c) 50%,#ababab 0) 1/0 100vw/0 calc(100vw + var(--g));
I know it looks scary, but let’s dissect that line and you will see it’s not that difficult. The above is the shorthand for the following:
border-image-source: linear-gradient(90deg,var(--c) 50%,#ababab 0);
border-image-slice: 1;
border-image-width: 0 100vw;
border-image-outset: 0 calc(100vw + var(--g));
From the MDN page, we read:
The
border-image
CSS property draws an image around a given element. It replaces the element’s regular border.
Our image will be a gradient having two colors — the main one (defined by --c
), and a gray color. We need the border image to cover the whole space of the input horizontally, so we use a big value for the left and right width (100vw
) while we keep the top and bottom at (0
).
But the border-image-width
is limited to the element size. To overcome this, we need to also use a big value for the border-image-outset
to increase the space available for the border image. From MDN again:
The
border-image-outset
CSS property sets the distance by which an element’s border image is set out from its border box.The parts of the border image that are rendered outside the element’s border box with
border-image-outset
do not trigger overflow scrollbars and don’t capture mouse events.
When you first see the slider, it looks like we’re increasing the main color on the left, but in reality we’re sliding a fixed gradient that’s overflowing our element.
The following demo provides an overview of what’s happening under the hood.
Drag the thumb and slide it to see how things are moving. I’m using a small value for the width and outset so we can easily understand the trick.
Also, note that the outset needs to be bigger than the width to have the gap. For this reason, it’s defined to be equal to the width plus the value of the gap.
By adding overflow: hidden
to the input element and using a big value, the illusion is perfect, as shown below.
What about the
border-image-slice
? Why the value of1
?
This property is a bit tricky, but mandatory when using border-image
. In our case, this value isn’t very relevant and a small positive value will do the job. I have a detailed Stack Overflow answer if you want to learn more about it.
The last step is to decrease the size of the bar to match the size we defined by the variable --l
. For this, we’re going to use clip-path
:
clip-path:
polygon(
0 calc(50% + var(--l)/2),
-100vw calc(50% + var(--l)/2),
-100vw calc(50% - var(--l)/2),
0 calc(50% - var(--l)/2),
0 0,100% 0,
100% calc(50% - var(--l)/2),
100vw calc(50% - var(--l)/2),
100vw calc(50% + var(--l)/2),
100% calc(50% + var(--l)/2),
100% 100%,0 100%);
The image below provides an overview of the different points to understand the shape of the polygon.
That’s it! We have a custom range slider with a few lines of code that you can easily control by adjusting a few variables.
What about some subtle animation when we interact with the slider? It doesn’t need a lot of code, and it will enhance the UX of the slider.
First, we’re going to transform the thumb from a border-only circle into a full circle when we click on it. For this, we increase the spread value of the box-shadow
. Remember that we’ve used box-shadow
to define the border of the thumb:
box-shadow: 0 0 0 var(--l) inset var(--c);
We update the var(--l)
to var(--s)
using the :active
selector and the :focus-visible
. The latter is related to keyboard navigation and allows us to have the same effect whether we use the mouse or the keyboard.
The code is as follows:
input[type="range" i]::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
transition: .3s;
}
input[type="range" i]::-moz-range-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
transition: .3s;
}
input:active::-webkit-slider-thumb,
input:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
}
input:active::-moz-range-thumb,
input:focus-visible::-moz-range-thumb {
box-shadow: 0 0 0 var(--s) inset var(--c);
}
It’s a bit lengthy for a box-shadow
transition, right? We can optimize it using a CSS variable:
input[type="range" i]::-webkit-slider-thumb {
box-shadow: 0 0 0 var(--_b,var(--s)) inset var(--c);
transition: .3s;
}
input[type="range" i]::-moz-range-thumb {
box-shadow: 0 0 0 var(--_b,var(--s)) inset var(--c);
transition: .3s;
}
input:active,
input:focus-visible {
--_b: var(--s);
}
I’m expressing the spread value using a variable, and I’m simply updating that variable on :active
and :focus-visible
.
I’m also going to add a little animation to the color. I’ll make it a bit darker on :hover
. For this, I won’t update the color, but rather mix it with black using the new color-mix()
function. This trick allows us to use the main color defined by --c
rather than define a new dark color for each slider manually:
--_c: color-mix(in srgb, var(--c), #000 var(--p,0%));
I’m defining a new variable that will replace the --c
in the code. Then by adjusting the percentage of the black color (#000
) using the variable --p
, I’m controlling the “darkness” of the color:
input:focus-visible,
input:hover{
--p: 25%;
}
This feature isn’t yet supported in every browser, so the use of a fallback is highly recommended:
@supports not (color: color-mix(in srgb,red,red)) {
input {
--_c: var(--c); /* if no support we keep the color as defined */
}
}
Our range slider is now perfect!
We’ve reached the end and haven’t had to deal with any complex browser-related implementation! We identified the selector of the thumb element and, using a few CSS tricks, we styled the whole range slider with it. Let’s not forget that we did this using only the <input>
element, so we don’t have to worry about any accessibility issues, as we’ve kept the native functionality. The slider supports keyboard navigation without a problem.
Here are more examples of sliders using the same technique. I’ll let you dissect their code as an exercise.
Original article source at: https://www.sitepoint.com/
1684244308
Slider Button v2.0.0
This package provides an easy implementation of a Slider Button to cancel current transaction or screen. Highly customizable iphone alike looking widget.
This is a Circle type widget. You just need to define the border radius to swap between rectangle and circle type widget.
import 'package:slider_button/slider_button.dart';
Center(child: SliderButton(
action: () {
///Do something here
Navigator.of(context).pop();
},
label: Text(
"Slide to cancel Event",
style: TextStyle(
color: Color(0xff4a4a4a), fontWeight: FontWeight.w500, fontSize: 17),
),
icon: Text(
"x",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
fontSize: 44,
),
),
));
This is a Rectangle type widget.
import 'package:slider_button/slider_button.dart';
SliderButton(
action: () {
///Do something here OnSlide
},
///Put label over here
label: Text(
"Slide to cancel !",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: 17),
),
icon: Center(
child: Icon(
Icons.power_settings_new,
color: Colors.white,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
)),
///Change All the color and size from here.
width: 230,
radius: 10,
buttonColor: Color(0xffd60000),
backgroundColor: Color(0xff534bae),
highlightedColor: Colors.white,
baseColor: Colors.red,
);
There are several options that allow for more control:
Properties | Default | Description |
---|---|---|
action | null | (required) Define an action after slidding a button |
child | null | For more customizable button add your own widget |
vibrationFlag | false | controls vibration on successful dismissed |
height | null ?? 70 | Gives a height to a widget |
width | null ?? 250 | Gives a width to a widget |
backgroundColor | Color(0xffececec) | Gives a background color to a widget |
baseColor | Color(0xff4a4a4a) | Gives a shimmer base color to a widget |
highlightedColor | Colors.white | Gives a shimmer highlighted color to a widget |
buttonColor | Colors.black | Gives a color to a slidder button |
label | null | A text widget which assigns a label. |
alignLabel | Alignment(0.4, 0) | Aligns text label |
boxShadow | null | Gives a shadow to a slidder button |
icon | null | A widget to provide an icon to a button |
shimmer | false | enables/disables shimmer effect on the label |
dismissible | true | Make it false if you want maintain the widget in the tree |
buttonSize | null ?? 60 | Gives size to a button |
dismissThresholds | 1.0 | The offset threshold when it should be considered dismissed |
👍 Contribution
Run this command:
With Flutter:
$ flutter pub add slider_button
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
slider_button: ^2.0.0
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:slider_button/slider_button.dart';
import 'package:flutter/material.dart';
import 'package:slider_button/slider_button.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: MainApp());
}
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SliderButton(
action: () {
///Do something here OnSlide
print("working");
},
///Put label over here
label: Text(
"Slide to cancel !",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: 17),
),
icon: Center(
child: Icon(
Icons.power_settings_new,
color: Colors.white,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
)),
//Put BoxShadow here
boxShadow: BoxShadow(
color: Colors.black,
blurRadius: 4,
),
//Adjust effects such as shimmer and flag vibration here
shimmer: true,
vibrationFlag: true,
///Change All the color and size from here.
width: 230,
radius: 10,
buttonColor: Color(0xffd60000),
backgroundColor: Color(0xff534bae),
highlightedColor: Colors.white,
baseColor: Colors.red,
)));
}
}
Download Details:
Author: anirudhsharma392
Source Code: https://github.com/anirudhsharma392/Slider-Button
1684172405
Flutter slider drawer
A Flutter package with custom implementation of the Slider Drawer Menu
To start using this package, add flutter_slider_drawer
dependency to your pubspec.yaml
dependencies:
flutter_slider_drawer: '<latest_release>'
Features
SliderAppBar
widgetisCupertino: true
Code
Widget build(BuildContext context) {
return Scaffold(
body: SliderDrawer(
key: _key,
appBar: SliderAppBar(
appBarColor: Colors.white,
title: Text(title,
style: const TextStyle(
fontSize: 22, fontWeight: FontWeight.w700))),
slider: Container(color: Colors.red),
child: Container(color: Colors.amber),
));
}
Slider open
SliderOpen.LEFT_TO_RIGHT | SliderOpen.RIGHT_TO_LEFT | SliderOpen.TOP_TO_BOTTOM |
---|---|---|
![]() | ![]() | ![]() |
class _MyAppState extends State<MyApp> {
GlobalKey<SliderDrawerState> _key = GlobalKey<SliderDrawerState>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SliderDrawer(
key: _key,
appBar: SliderAppBar(
appBarColor: Colors.white,
title: Text('Title',
style:
const TextStyle(fontSize: 22, fontWeight: FontWeight.w700))),
slider: Container(color: Colors.red),
child: Container(color: Colors.amber),
));
}
}
_key.currentState.closeDrawer();
_key.currentState.openDrawer();
_key.currentState.toggle();
_key.currentState.isDrawerOpen();
_key.currentState.animationController
BSD 2-Clause License
Run this command:
With Flutter:
$ flutter pub add flutter_slider_drawer
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
flutter_slider_drawer: ^2.1.3
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:flutter_slider_drawer/flutter_slider_drawer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slider_drawer/flutter_slider_drawer.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
final GlobalKey<SliderDrawerState> _sliderDrawerKey =
GlobalKey<SliderDrawerState>();
late String title;
@override
void initState() {
title = "Home";
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(fontFamily: 'BalsamiqSans'),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SliderDrawer(
appBar: SliderAppBar(
appBarColor: Colors.white,
title: Text(title,
style: const TextStyle(
fontSize: 22, fontWeight: FontWeight.w700))),
key: _sliderDrawerKey,
sliderOpenSize: 179,
slider: _SliderView(
onItemClick: (title) {
_sliderDrawerKey.currentState!.closeSlider();
setState(() {
this.title = title;
});
},
),
child: _AuthorList()),
),
);
}
}
class _SliderView extends StatelessWidget {
final Function(String)? onItemClick;
const _SliderView({Key? key, this.onItemClick}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
padding: const EdgeInsets.only(top: 30),
child: ListView(
children: <Widget>[
const SizedBox(
height: 30,
),
CircleAvatar(
radius: 65,
backgroundColor: Colors.grey,
child: CircleAvatar(
radius: 60,
backgroundImage: Image.network(
'https://nikhilvadoliya.github.io/assets/images/nikhil_1.webp')
.image,
),
),
const SizedBox(
height: 20,
),
const Text(
'Nick',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
const SizedBox(
height: 20,
),
...[
Menu(Icons.home, 'Home'),
Menu(Icons.add_circle, 'Add Post'),
Menu(Icons.notifications_active, 'Notification'),
Menu(Icons.favorite, 'Likes'),
Menu(Icons.settings, 'Setting'),
Menu(Icons.arrow_back_ios, 'LogOut')
]
.map((menu) => _SliderMenuItem(
title: menu.title,
iconData: menu.iconData,
onTap: onItemClick))
.toList(),
],
),
);
}
}
class _SliderMenuItem extends StatelessWidget {
final String title;
final IconData iconData;
final Function(String)? onTap;
const _SliderMenuItem(
{Key? key,
required this.title,
required this.iconData,
required this.onTap})
: super(key: key);
@override
Widget build(BuildContext context) {
return ListTile(
title: Text(title,
style: const TextStyle(
color: Colors.black, fontFamily: 'BalsamiqSans_Regular')),
leading: Icon(iconData, color: Colors.black),
onTap: () => onTap?.call(title));
}
}
class _AuthorList extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<Quotes> quotesList = [];
quotesList.add(Quotes(Colors.amber, 'Amelia Brown',
'Life would be a great deal easier if dead things had the decency to remain dead.'));
quotesList.add(Quotes(Colors.orange, 'Olivia Smith',
'That proves you are unusual," returned the Scarecrow'));
quotesList.add(Quotes(Colors.deepOrange, 'Sophia Jones',
'Her name badge read: Hello! My name is DIE, DEMIGOD SCUM!'));
quotesList.add(Quotes(Colors.red, 'Isabella Johnson',
'I am about as intimidating as a butterfly.'));
quotesList.add(Quotes(Colors.purple, 'Emily Taylor',
'Never ask an elf for help; they might decide your better off dead, eh?'));
quotesList
.add(Quotes(Colors.green, 'Maya Thomas', 'Act first, explain later'));
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: ListView.separated(
scrollDirection: Axis.vertical,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
itemBuilder: (builder, index) {
return LimitedBox(
maxHeight: 150,
child: Container(
decoration: BoxDecoration(
color: quotesList[index].color,
borderRadius: const BorderRadius.all(
Radius.circular(10.0),
)),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12),
child: Text(
quotesList[index].author,
style: const TextStyle(
fontFamily: 'BalsamiqSans_Blod',
fontSize: 30,
color: Colors.white),
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Text(
quotesList[index].quote,
style: const TextStyle(
fontFamily: 'BalsamiqSans_Regular',
fontSize: 15,
color: Colors.white),
),
)
],
),
),
);
},
separatorBuilder: (builder, index) {
return const Divider(
height: 10,
thickness: 0,
);
},
itemCount: quotesList.length),
);
}
}
class Quotes {
final MaterialColor color;
final String author;
final String quote;
Quotes(this.color, this.author, this.quote);
}
class Menu {
final IconData iconData;
final String title;
Menu(this.iconData, this.title);
}
Download Details:
Author: NikhilVadoliya
Source Code: https://github.com/NikhilVadoliya/Flutter_slider_drawer
1680886505
В этой статье я показал, как слайдер сравнения изображений создается с использованием HTML, CSS и JavaScript. Ранее я поделился с вами тем, как создавать различные типы галерей изображений и слайдеров .
Слайдер сравнения изображений в основном помогает различать два изображения или продукта. В результате пользователь может легко понять, какой из двух продуктов лучше.
Как вы можете видеть на изображении выше, это красивый слайдер для сравнения изображений в HTML и CSS. Популярность этого вида дизайна постепенно растет.
Этот тип дизайна широко используется в различных отраслях, таких как сайты электронной коммерции или сайты с обзорами продуктов. Здесь вы можете легко определить разницу между двумя типами продуктов или изображений.
Самым важным моментом этого слайдера является то, что изображения можно делать как большими, так и маленькими по мере необходимости. Ниже я дал живую демонстрацию этого дизайна.
Под статьей находится необходимый исходный код. Если вы хотите загрузить исходный код, вы можете использовать кнопку загрузки внизу статьи.
В следующем уроке я показал вам, как создать красивый слайдер для сравнения изображений с помощью JavaScript. Позвольте мне рассказать вам кое-что об этом дизайне, прежде чем поделиться уроком.
Сначала я разработал эту страницу. Затем я сделал красивую коробку. Это поле является базовой структурой слайдера , где я использовал два изображения. Между этими двумя изображениями есть граница и кнопка управления.
Я разработал весь слайдер с помощью HTML и CSS. Здесь мы использовали некоторое количество JavaScript для реализации сравнения.
Я использовал следующие коды CSS для разработки веб-страницы. Здесь фоновый цвет я использовал светло-голубой и высоту 100vh.
*,
*:before,
*:after{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
height: 100vh;
display: grid;
background: #d1ebec;
place-items: center;
}
Следующие коды HTML и CSS используются для создания большей части структуры слайдера сравнения изображений. Здесь я использовал ползунок высотой 62,5vmin и шириной 100vmin. Граница в 5 пикселей и рамка теней были использованы для усиления красоты.
<div class=”container”>
</div>
.container{
height: 62.5vmin;
width: 100vmin;
position: relative;
overflow: hidden;
border: 5px solid #bfc0c1;
box-shadow:-3px 5px 15px #000;
}
Теперь я сначала добавил изображение. Его длина и высота остаются равными ползунку.
<img src=”img1.jpg”>
img{
width: 100%;
height: 100%;
position: absolute;
}
Я использовал второе изображение, используя следующие коды. Я использовал clip-path , так что здесь можно увидеть половину второго изображения. Если вы не знаете основную концепцию clip-path: polygon, то следуйте изображению ниже.
<img id=”my-img” src=”img2.jpg”>
#my-img{
clip-path: polygon(0 0 , 50% 0, 50% 100%, 0 100%);
}
Теперь я создал кнопку управления, которая будет управлять диапазоном этого ползунка. Здесь минимальное значение, которое я дал, равно нулю, а максимальное — 100. Здесь используется значение 50, что означает, что по умолчанию оно будет в середине ползунка.
<input type=”range” min=”0″ max=”100″ value=”50″ id=”slider” oninput=”slide()”>
#slider{
position: relative;
-webkit-appearance: none;
width: calc( 100% + 40px);
height: 100%;
margin-left: -20px;
background-color: transparent;
outline: none;
}
#slider::-webkit-slider-thumb{
-webkit-appearance: none;
height: 45px;
width: 45px;
background: url(“slider-icon.svg”),
rgba(255,255,255,0.3);
border: 4px solid white;
border-radius: 50%;
background-size: contain;
cursor: pointer;
}
Я реализовал этот слайдер сравнения изображений, используя следующий JavaScript. Сначала я установил константу идентификатора кнопки управления.
Ниже я привел картинку, чтобы лучше понять структуру JavaScript.
function slide(){
let slideValue = document.getElementById(“slider”).value;
document.getElementById(“my-img”).style.clipPath = “polygon(0 0,” + slideValue + “% 0,” + slideValue + “% 100%, 0 100%)”;
console.log(“polygon(0 0,” + slideValue + “% 0,” + slideValue + “% 100%, 0 100%)”);
}
Надеюсь, вы узнали из приведенного выше руководства, как я сделал этот слайдер сравнения изображений, используя HTML, CSS и JavaScript. Если у вас есть какие-либо проблемы, вы можете определенно сообщить мне, комментируя.
Оригинальный источник статьи: https://foolishdeveloper.com/
1680882721
在本文中,我展示了如何使用 HTML、CSS 和 JavaScript 创建图像比较滑块。早些时候,我与您分享了如何创建不同类型的图片库和滑块。
图像比较滑块基本上有助于区分两个图像或产品。结果,用户可以很容易地了解这两种产品中哪一种更好。
正如您在上图中看到的,它是一个漂亮的 HTML 和 CSS 单图像比较滑块。这种设计的流行度正在慢慢增加。
这种设计广泛应用于电子商务网站或产品评论网站等各个行业。在这里您可以很容易地分辨出两种类型的产品或图像之间的区别。
这个滑块最重要的一点是图像可以根据需要调整大小。下面我给出了这个设计的现场演示。
文章下方是所需的源代码。如果你想下载源代码,可以使用文章底部的下载按钮。
在下面的教程中,我向您展示了如何使用 JavaScript 创建漂亮的图像比较滑块。在分享教程之前,让我告诉你一些关于这个设计的事情。
首先我设计了那个页面。然后我做了一个漂亮的盒子。该框是滑块的基本结构,我在其中使用了两个图像。这两张图片中间有一个边框,还有一个控制按钮。
我在 HTML 和 CSS 的帮助下设计了整个滑块。这里我们使用了一些 JavaScript 来实现比较。
我使用以下 CSS 代码来设计网页。这里的背景颜色我使用了浅蓝色,高度为 100vh。
*,
*:before,
*:after{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
height: 100vh;
display: grid;
background: #d1ebec;
place-items: center;
}
以下 HTML 和 CSS 代码用于创建图像比较滑块的大部分结构。在这里,我使用了滑块高度 62.5vmin 和宽度 100vmin。使用了 5 像素的边框和阴影框来增强美感。
<div class=”container”>
</div>
.container{
height: 62.5vmin;
width: 100vmin;
position: relative;
overflow: hidden;
border: 5px solid #bfc0c1;
box-shadow:-3px 5px 15px #000;
}
现在我先添加了图像。它的长度和高度与滑块保持相等。
<img src=”img1.jpg”>
img{
width: 100%;
height: 100%;
position: absolute;
}
我使用以下代码使用了第二张图片。我使用了剪辑路径,以便可以在此处看到第二张图片的一半。如果你不知道 clip-path: polygon 的基本概念,那么请按照下图进行操作。
<img id=”my-img” src=”img2.jpg”>
#my-img{
clip-path: polygon(0 0 , 50% 0, 50% 100%, 0 100%);
}
现在我已经创建了一个控制按钮来控制这个滑块的范围。这里我给出的最小值为零,最大值为 100。这里使用值 50,这意味着默认情况下它将位于滑块的中间。
<input type=”range” min=”0″ max=”100″ value=”50″ id=”slider” oninput=”slide()”>
#slider{
position: relative;
-webkit-appearance: none;
width: calc( 100% + 40px);
height: 100%;
margin-left: -20px;
background-color: transparent;
outline: none;
}
#slider::-webkit-slider-thumb{
-webkit-appearance: none;
height: 45px;
width: 45px;
background: url(“slider-icon.svg”),
rgba(255,255,255,0.3);
border: 4px solid white;
border-radius: 50%;
background-size: contain;
cursor: pointer;
}
我已经使用以下 JavaScript 实现了这个图像比较滑块。首先,我设置了控制按钮的 id 常量。
下面我给出了一张图来更好地理解 JavaScript 的结构。
function slide(){
let slideValue = document.getElementById(“slider”).value;
document.getElementById(“my-img”).style.clipPath = “polygon(0 0,” + slideValue + “% 0,” + slideValue + “% 100%, 0 100%)”;
console.log(“polygon(0 0,” + slideValue + “% 0,” + slideValue + “% 100%, 0 100%)”);
}
希望您从上面的教程中了解了我是如何使用 HTML CSS 和 JavaScript 制作这个图像比较滑块的。如果您有任何问题,您绝对可以通过评论让我知道。
文章原文出处:https: //foolishdeveloper.com/
1680853686
In this article, I have shown how Image Comparison Slider is created using HTML, CSS, and JavaScript. Earlier I shared with you how to create different types of image galleries and sliders.
Image Comparison Slider basically helps to differentiate between two images or products. As a result, the user can easily understand which of the two products is better.
As you can see in the image above it is a beautiful one image comparison slider in HTML and CSS. The popularity of this type of design is slowly increasing.
This type of design is widely used in various industries such as e-commerce sites or product review sites. Here you can easily tell the difference between the two types of products or images.
The most important point of this slider is that the images can be made as big and small as needed. Below I have given a live demo of this design.
Below the article is the required source code. If you want to download the source code, you can use the download button at the bottom of the article.
In the following tutorial, I have shown you how to create a beautiful image comparison slider using JavaScript. Let me tell you something about this design before sharing the tutorial.
First I designed that page. Then I made a beautiful box. That box is the basic structure of the slider where I used two images. There is a border in the middle of these two images and there is a control button.
I designed the whole slider with the help of HTML and CSS. Here we have used some amount of JavaScript to implement Comparison.
I have used the following CSS codes to design the webpage. Here background-color I have used light blue and height 100vh has been used.
*,
*:before,
*:after{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
height: 100vh;
display: grid;
background: #d1ebec;
place-items: center;
}
The following HTML and CSS codes are used to create most of the structure of the Image Comparison Slider. Here I have used the slider height 62.5vmin and width 100vmin. A border of 5 pixels and a box of shadows have been used to enhance the beauty.
<div class=”container”>
</div>
.container{
height: 62.5vmin;
width: 100vmin;
position: relative;
overflow: hidden;
border: 5px solid #bfc0c1;
box-shadow:-3px 5px 15px #000;
}
Now I have added the image first. Its length and height are kept equal with the slider.
<img src=”img1.jpg”>
img{
width: 100%;
height: 100%;
position: absolute;
}
I have used the second image using the following codes. I have used a clip-path so that half of the second image can be seen here. If you do not know the basic concept of clip-path: polygon, then follow the image below.
<img id=”my-img” src=”img2.jpg”>
#my-img{
clip-path: polygon(0 0 , 50% 0, 50% 100%, 0 100%);
}
Now I have created a control button that will control the range of this slider. Here the minimum value I gave is zero and the maximum is 100. Here value 50 is used which means by default it will be in the middle of the slider.
<input type=”range” min=”0″ max=”100″ value=”50″ id=”slider” oninput=”slide()”>
#slider{
position: relative;
-webkit-appearance: none;
width: calc( 100% + 40px);
height: 100%;
margin-left: -20px;
background-color: transparent;
outline: none;
}
#slider::-webkit-slider-thumb{
-webkit-appearance: none;
height: 45px;
width: 45px;
background: url(“slider-icon.svg”),
rgba(255,255,255,0.3);
border: 4px solid white;
border-radius: 50%;
background-size: contain;
cursor: pointer;
}
I have implemented this Image Comparison Slider using the following JavaScript. First I set a constant of the id of the control button.
Below I have given a picture to better understand the structure of JavaScript.
function slide(){
let slideValue = document.getElementById(“slider”).value;
document.getElementById(“my-img”).style.clipPath = “polygon(0 0,” + slideValue + “% 0,” + slideValue + “% 100%, 0 100%)”;
console.log(“polygon(0 0,” + slideValue + “% 0,” + slideValue + “% 100%, 0 100%)”);
}
Hopefully, you have learned from the above tutorial how I made this Image Comparison Slider using HTML CSS, and JavaScript. If you have any problems, you can definitely let me know by commenting.
Original article source at: https://foolishdeveloper.com/
1680797935
Flutter Package to add the Squiggly Seekbar (introduced in Android 13 for the Media Player) as a Widget
Flutter rebuild of the Squiggly Seekbar introduced in Android 13 for the Media Player.
flutter pub add squiggly_slider
or manually add the dependency to your pubspec.yaml
file.
dependencies:
squiggly_slider: ^1.0.0
import the package
import 'package:squiggly_slider/squiggly_slider.dart';
and then use it as a drop in replacement for the normal slider
SquigglySlider(
//... normal Slider Widget properties ...
squiggleAmplitude: 5.0,
squiggleWavelength: 5.0,
squiggleSpeed: 0.3,
),
contributions (PRs) are welcome.
Run this command:
With Flutter:
$ flutter pub add squiggly_slider
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
squiggly_slider: ^1.0.1
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:squiggly_slider/slider.dart';
import 'package:squiggly_slider/squiggly_slider_track_shape.dart';
import 'package:flutter/material.dart';
import 'package:squiggly_slider/slider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Squiggly Slider Demo'),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
AmplitudeSquiggleSlider(),
WavelengthSquiggleSlider(),
],
),
),
);
}
}
class AmplitudeSquiggleSlider extends StatefulWidget {
const AmplitudeSquiggleSlider({super.key});
@override
State<AmplitudeSquiggleSlider> createState() =>
_AmplitudeSquiggleSliderState();
}
class _AmplitudeSquiggleSliderState extends State<AmplitudeSquiggleSlider> {
double _amplitude = 0.5;
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Amplitude'),
SquigglySlider(
value: _amplitude,
min: 0,
max: 20,
squiggleAmplitude: _amplitude,
squiggleWavelength: 10,
squiggleSpeed: 0.2,
label: 'Amplitude',
onChanged: (double value) {
setState(() {
_amplitude = value;
});
},
),
],
);
}
}
class WavelengthSquiggleSlider extends StatefulWidget {
const WavelengthSquiggleSlider({super.key});
@override
State<WavelengthSquiggleSlider> createState() =>
_WavelengthSquiggleSliderState();
}
class _WavelengthSquiggleSliderState extends State<WavelengthSquiggleSlider> {
double _wavelength = 10;
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Wavelength'),
SquigglySlider(
value: _wavelength,
min: 0,
max: 30,
squiggleAmplitude: 10,
squiggleWavelength: _wavelength,
squiggleSpeed: 0.01,
label: 'Wavelength',
onChanged: (double value) {
setState(() {
_wavelength = value;
});
},
),
],
);
}
}
Download Details:
Author: hannesgith
Source Code: https://github.com/hannesgith/squiggly_slider
1680797702
Slider Button v2.0.0
This package provides an easy implementation of a Slider Button to cancel current transaction or screen. Highly customizable iphone alike looking widget.
This is a Circle type widget. You just need to define the border radius to swap between rectangle and circle type widget.
import 'package:forked_slider_button/forked_slider_button.dart';
Center(child: SliderButton(
action: () {
///Do something here
Navigator.of(context).pop();
},
label: Text(
"Slide to cancel Event",
style: TextStyle(
color: Color(0xff4a4a4a), fontWeight: FontWeight.w500, fontSize: 17),
),
icon: Text(
"x",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
fontSize: 44,
),
),
));
This is a Rectangle type widget.
import 'package:forked_slider_button/forked_slider_button.dart';
SliderButton(
action: () {
///Do something here OnSlide
},
///Put label over here
label: Text(
"Slide to cancel !",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: 17),
),
icon: Center(
child: Icon(
Icons.power_settings_new,
color: Colors.white,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
)),
///Change All the color and size from here.
width: 230,
radius: 10,
buttonColor: Color(0xffd60000),
backgroundColor: Color(0xff534bae),
highlightedColor: Colors.white,
baseColor: Colors.red,
);
There are several options that allow for more control:
Properties | Default | Description |
---|---|---|
action | null | (required) Define an action after slidding a button |
child | null | For more customizable button add your own widget |
vibrationFlag | false | controls vibration on successful dismissed |
height | null ?? 70 | Gives a height to a widget |
width | null ?? 250 | Gives a width to a widget |
backgroundColor | Color(0xffececec) | Gives a background color to a widget |
baseColor | Color(0xff4a4a4a) | Gives a shimmer base color to a widget |
highlightedColor | Colors.white | Gives a shimmer highlighted color to a widget |
buttonColor | Colors.black | Gives a color to a slidder button |
label | null | A text widget which assigns a label. |
alignLabel | Alignment(0.4, 0) | Aligns text label |
boxShadow | null | Gives a shadow to a slidder button |
icon | null | A widget to provide an icon to a button |
shimmer | false | enables/disables shimmer effect on the label |
dismissible | true | Make it false if you want maintain the widget in the tree |
buttonSize | null ?? 60 | Gives size to a button |
dismissThresholds | 1.0 | The offset threshold when it should be considered dismissed |
👍 Contribution
Run this command:
With Flutter:
$ flutter pub add forked_slider_button
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get
):
dependencies:
forked_slider_button: ^2.0.2
Alternatively, your editor might support flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:forked_slider_button/forked_slider_button.dart';
import 'package:flutter/material.dart';
import 'package:forked_slider_button/forked_slider_button.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: MainApp());
}
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SliderButton(
action: () {
///Do something here OnSlide
print("working");
},
///Put label over here
label: Text(
"Slide to cancel !",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: 17),
),
icon: Center(
child: Icon(
Icons.power_settings_new,
color: Colors.white,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
)),
//Put BoxShadow here
boxShadow: BoxShadow(
color: Colors.black,
blurRadius: 4,
),
//Adjust effects such as shimmer and flag vibration here
shimmer: true,
vibrationFlag: true,
///Change All the color and size from here.
width: 230,
radius: 10,
buttonColor: Color(0xffd60000),
backgroundColor: Color(0xff534bae),
highlightedColor: Colors.white,
baseColor: Colors.red,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Example of a wide button"),
),
SliderButton(
action: () {
///Do something here OnSlide
print("working");
},
///Put label over here
label: Text(
"Slide to cancel !",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: 17),
),
buttonWidth: 84,
height: 44,
buttonSize: 44,
child: Container(
width: 80,
margin: EdgeInsets.all(2),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10),
),
child: Icon(
Icons.power_settings_new,
color: Colors.white,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
),
),
//Put BoxShadow here
boxShadow: BoxShadow(
color: Colors.black,
blurRadius: 4,
),
//Adjust effects such as shimmer and flag vibration here
shimmer: true,
vibrationFlag: true,
///Change All the color and size from here.
width: 230,
radius: 10,
buttonColor: Color(0xffd60000),
backgroundColor: Color(0xff534bae),
highlightedColor: Colors.white,
baseColor: Colors.red,
),
],
),
),
);
}
}
Download Details:
Author: anirudhsharma392
Source Code: https://github.com/anirudhsharma392/Slider-Button
1678560960
В этой статье вы узнаете, как создать автоматический слайдер изображений с помощью HTML CSS и кода JavaScript. Ранее я поделился с вами еще многими типами ручных и автоматических слайдеров изображений . Как и другие проекты, я надеюсь, вам понравится этот дизайн.
Слайдер изображений — это распространенный веб-элемент, который в настоящее время используется на многих веб-сайтах. Он в основном используется для слайд-шоу на главной странице сайта. Этот тип автоматического слайд-шоу изображений также используется для организации большого количества изображений в галерее. Если вы хотите узнать больше о javascript, ознакомьтесь с моими лучшими проектами HTML, CSS и javascript .
Существует два типа ползунков изображений: автоматический и ручной. В случае автоматического ползунка изображения изображение будет автоматически меняться через равные промежутки времени. В случае с мануалом менять изображение нужно с помощью кнопок Next и Previous.
При этом изображение можно менять автоматически и вручную. Это означает, что он автоматически изменит изображение, и вы также можете изменить изображение, используя кнопки «Далее» и «Предварительный просмотр» по отдельности.
Дизайн можно создать только с помощью HTML и CSS, но в данном случае я использовал программный код JavaScript.
Если вы хотите узнать, как работают эти автоматические слайд-шоу изображений , вы можете посмотреть живую демонстрацию ниже. Ниже я дал исходный код, так что вы можете скопировать их, если хотите. Вы также можете скачать код с помощью кнопки загрузки внизу статьи.
Как вы можете видеть в демо выше, это очень простой слайдер изображений с автоматической и ручной сменой изображений.
В этом случае я использовал в общей сложности пять изображений, но вы можете использовать гораздо больше, если хотите. Изображение будет меняться автоматически каждые 5 секунд. Также есть две кнопки для смены изображения.
Если вы знаете основы HTML, CSS и JavaScript, вы легко разберетесь в этом дизайне. Чтобы создать этот автоматический слайдер изображений, сначала вам нужно создать файл HTML и CSS.
В данном случае я не создавал отдельный файл JavaScript, но вы можете создать отдельный файл, если хотите.
Я использовал небольшой код HTML и CSS ниже, чтобы создать фон для этого слайдера. В этом случае я использовал ползунок высотой 256 пикселей и шириной 500 пикселей.
Я не использовал разные цвета фона. Если вы видели демонстрацию, вы поймете, что вокруг этого слайда была использована тень, для которой я использовал box-shadow: 0 0 30px rgba(0, 0, 0, 0.3) здесь.
<div id=”slider”>
</div>
body {
margin: 10%;
}
#slider {
position: relative;
width: 500px;
height: 265px;
overflow: hidden;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
}
Я добавил изображения в этот автоматический слайдер изображений, используя приведенный ниже код, и разработал эти изображения. Я использовал в общей сложности пять изображений, которые вы можете увеличивать или уменьшать по своему усмотрению.
Если вы внимательно посмотрите на приведенный ниже код CSS, вы поймете, что я использовал Slider Ul Width 10000%.
Вы можете задаться вопросом, почему я использовал здесь 10 000%. Внимательно посмотрите на изображение ниже, чтобы понять, почему и как работает этот ползунок.
<ul id=”slideWrap”>
<li><img src=”img1.jpg” alt=””></li>
<li><img src=”img2.jpg” alt=””></li>
<li><img src=”img3.jpg” alt=””></li>
<li><img src=”img4.jpg” alt=””></li>
<li><img src=”img5.jpg” alt=””></li>
</ul>
В этом случае высота изображения составляет 256 пикселей, а ширина — 500 пикселей. Конечно, в этом случае вы будете использовать одинаковый размер каждого изображения.
#slider ul {
position: relative;
list-style: none;
height: 100%;
width: 10000%;
padding: 0;
margin: 0;
transition: all 750ms ease;
left: 0;
}
#slider ul li {
position: relative;
height: 100%;
float: left;
}
#slider ul li img{
width: 500px;
height: 265px;
}
Теперь мы добавим к этому слайдеру кнопки Previs и Next. Приведенный ниже код HTML и CSS помог добавить и спроектировать эти две кнопки.
<a id=”prev” href=”#”>≪</a>
<a id=”next” href=”#”>≫</a>
#slider #prev, #slider #next {
width: 50px;
line-height: 50px;
border-radius: 50%;
font-size: 2rem;
text-shadow: 0 0 20px rgba(0, 0, 0, 0.6);
text-align: center;
color: white;
text-decoration: none;
position: absolute;
top: 50%;
transform: translateY(-50%);
transition: all 150ms ease;
}
Я использовал небольшой CSS ниже, чтобы разместить эти две кнопки на своих местах. Я оставил кнопку «Предварительный просмотр» на расстоянии 10 пикселей от левого края.
Я оставил следующую кнопку на расстоянии 10 пикселей от правого края. В результате эти две кнопки расположены по обе стороны от ползунка.
#slider #prev {
left: 10px;
}
#slider #next {
right: 10px;
}
Я использовал следующий код CSS, чтобы использовать небольшой эффект наведения на фоне этих двух кнопок.
#slider #prev:hover, #slider #next:hover {
background-color: rgba(0, 0, 0, 0.5);
text-shadow: 0;
}
Пока мы его только оформили, теперь реализуем смену изображения этого слайдера.
var responsiveSlider = function() {
var slider = document.getElementById(“slider”);
var sliderWidth = slider.offsetWidth;
var slideList = document.getElementById(“slideWrap”);
var count = 1;
var items = slideList.querySelectorAll(“li”).length;
var prev = document.getElementById(“prev”);
var next = document.getElementById(“next”);
window.addEventListener(‘resize’, function() {
sliderWidth = slider.offsetWidth;
});
Прежде всего, мы заранее определимся, какая работа будет выполнена, нажав на кнопку «Далее». Если вы новичок, то прежде всего посмотрите на структуру кода ниже. Затем следуйте приведенным ниже объяснениям, которые помогут вам лучше понять.
var nextSlide = function() {
if(count < items) {
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = items) {
slideList.style.left = “0px”;
count = 1;
}
};
Как мы видели, в переменной nextSlide мы сохранили, как будет работать кнопка «Далее».
Во-первых, мы добавили значение if (count <items), этот код будет работать, когда количество изображений больше, чем count.
С помощью else if (count = items) мы определили, что произойдет, если предыдущая функция не сработает. Если и изображение, и количество одинаковы, то слайдер не изменится.
'count' - это количество раз, когда вы нажали на кнопку. Если вы нажмете на эту кнопку один раз, значение счетчика будет равно единице. Если вы нажмете три раза одновременно, значение учетной записи равно 3.
Мы решили, какие изменения произойдут, если мы нажмем кнопку «Далее». Теперь мы реализуем предыдущую кнопку.
Точно так же здесь мы определили, какой эффект будет работать, если вы нажмете на предыдущую кнопку.
var prevSlide = function() {
if(count > 1) {
count = count – 2;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = 1) {
count = items – 1;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
};
Определение того, какой эффект будет работать при нажатии кнопок «Назад» и «Далее» в этом автоматическом слайдере изображений. Теперь мы свяжем эти эффекты с двумя кнопками.
Как я уже говорил ранее, мы сохранили то, как кнопка «Далее» будет работать, в константе под названием «следующий слайдер». Теперь ниже мы указали, что если вы нажмете кнопку «Далее», эта константа будет работать.
next.addEventListener(“click”, function() {
nextSlide();
});
Мы сохранили то, что работает на предыдущей кнопке, в «prevSlide». Теперь ниже мы указали, что если вы нажмете на предыдущую кнопку, эта константа будет работать.
prev.addEventListener(“click”, function() {
prevSlide();
});
Поскольку это автоматический слайдер изображений , в данном случае я устроил автоматическое изменение изображения. Здесь я использовал 5000 т.е. 5 секунд. Это означает, что изображение будет меняться каждые 5 секунд. Если вы хотите, чтобы изображения менялись каждые 2 секунды, используйте здесь 2000 вместо 5000.
setInterval(function() {
nextSlide()
}, 8000);
};
window.onload = function() {
responsiveSlider();
}
Надеюсь, вы узнали из этого урока, как я создал этот красивый автоматический слайдер изображений , используя код HTML CSS и JavaScript. Если вы хотите загрузить необходимый исходный код, вы можете использовать кнопку загрузки ниже.
Если у вас есть какие-либо проблемы с пониманием того, как сделать этот автоматический слайдер изображений, вы обязательно можете сообщить мне об этом в комментариях.
Original article source at: https://foolishdeveloper.com/