Scrollbar

Содержание:

Scroll Bar Colors and Metrics

The system-defined color value, COLOR_SCROLLBAR, controls the color within a scroll bar shaft. Use the GetSysColor function to determine the color of the scroll bar shaft and the SetSysColors function to set the color of the scroll bar shaft. Note, however, that this change of color affects all scroll bars in the system.

You can get the dimensions of the bitmaps that the system uses in standard scroll bars by calling the GetSystemMetrics function. Following are the system metric values associated with scroll bars.

System metric Description
SM_CXHSCROLL Width of arrow bitmap on horizontal scroll bar
SM_CXHTHUMB Width of scroll box on horizontal scroll bar. This value retrieves the width a scroll bar that has a page size of zero.
SM_CXVSCROLL Width of arrow bitmap on vertical scroll bar
SM_CYHSCROLL Height of arrow bitmap on horizontal scroll bar
SM_CYVSCROLL Height of arrow bitmap on vertical scroll bar
SM_CYVTHUMB Height of scroll box on vertical scroll bar. This value retrieves the height of a scroll bar that has a page size of zero.

Custom Scrollbar Limitations and Alternatives

There are clearly some problems with creating custom scrollbars. The first would be the lack of cross-browser support. Other issues would be the lack of ability to add transitions or animations to the scrollbar and the fact your custom scrollbar won’t appear on mobile devices.

An alternative is hiding the default scrollbar and using a library, but this may effect performance when used as main scrollbar for your page. And there are other potential usability issues because these libraries rely on JavaScript to imitate the native scrollbar behavior.

Below I’ll go over two popular open-source libraries for making scrollbars.

SimpleBar Library

Grsmto/simplebar
Custom scrollbars vanilla javascript library with native scroll, done simple, lightweight, easy to use and cross-browser. — Grsmto/simplebar

GrsmtoGitHub

As the name tells you, SimpleBar is all about making it easy to create custom scrollbars. The only real downside here is that it doesn’t support usage as the main scrollbar for your website or for table, text area, or select HTML elements.

The main purpose of SimpleBar would be for creating custom scrollbars for things like dynamic chat applications or any other type of internal page element where you want scrolling.

KingSora/OverlayScrollbars
A javascript scrollbar plugin which hides native scrollbars, provides custom styleable overlay scrollbars and keeps the native functionality and feeling. — KingSora/OverlayScrollbars

KingSoraGitHub

Overlay Scrollbars is very similar to SimpleBar but has the added benefit of supporting the HTML body element. This means that you can use it for the main scrollbar of your website in addition to all the other features you would expect like cross-browser and mobile support.

Разные состояние скроллбара

Это селекторы псевдоклассов. Их можно применять к различным элементам скроллбара для изменения внешнего вида, когда скроллбар находится в разных состояниях.

  • horizontal — псевдокласс применяется к любым частям скроллбара, имеющим горизонтальную ориентацию.
  • vertical — псевдокласс применяется к любым частям скроллбара, которые имеют вертикальную ориентацию.
  • decrement — Псевдокласс декремента применяется к кнопкам и элементами трека скроллбара. Он указывает, будет ли кнопка или элемент трека уменьшать положение вида при использовании (например, вверх по вертикальной полосе прокрутки, влево по горизонтальной полосе прокрутки).
  • increment — Псевдокласс инкремента применяется к кнопкам и элементами трека скроллбара. Он указывает, будет ли кнопка или элемент трека увеличивать позицию вида при использовании (например, вниз на вертикальной полосе прокрутки, прямо на горизонтальной полосе прокрутки).
  • start — Этот псевдокласс применяется к кнопкам и фрагментам трека. Он сообщает, что объект находится перед ползунком.
  • end — Этот псевдокласс применяется к кнопкам и фрагментам трека. Он сообщает, что объект находится после ползунка.
  • double-button — Псевдокласс применяется к кнопкам и трекам. Он используется для определения является ли кнопка частью пары кнопок, которые находятся на одном конце скроллбара. Для элементов трека он указывает, примыкает ли элемент трека к паре кнопок.
  • single-button — Псевдокласс применяется к кнопкам и элементам трека. Он используется для определения того, находится ли кнопка в конце скроллбара. Для элементов дорожек указывает, примыкает ли элемент трека к одной кнопке.
  • no-button — Применяется к элементам трека, сообщает, что видимая часть трека приближается к краю скроллбара, другими словами, кнопки в конце трека нет.
  • corner-present — Применяется ко всем элементам скроллбара и указывает на наличие угла полосы прокрутки.
  • window-inactive — Применяется ко всем элементам скроллбара и сообщает, что окно со скроллбаром в данный момент активно. В последних версиях этот псевдокласс хорошо сочетается с . Мы планируем расширить его работу для любого контента и предложить в качестве нового стандартного псевдокласса.

#

Keyboard Interface for a Scroll Bar

A scroll bar control provides a built-in keyboard interface that enables the user to issue scrolling requests by using the keyboard; a standard scroll bar does not. When a scroll bar control has the keyboard focus, it sends WM_HSCROLL and WM_VSCROLL messages to its parent window when the user presses the arrow keys. The request code is sent with each message corresponding to the arrow key the user has pressed. Following are the arrow keys and their corresponding request codes.

Arrow key Request code
DOWN SB_LINEDOWN or SB_LINERIGHT
END SB_BOTTOM
HOME SB_TOP
LEFT SB_LINEUP or SB_LINELEFT
PGDN SB_PAGEDOWN or SB_PAGERIGHT
PGUP SB_PAGEUP or SB_PAGELEFT
RIGHT SB_LINEDOWN or SB_LINERIGHT
UP SB_LINEUP or SB_LINELEFT

Note

The keyboard interface of a scroll bar control sends the SB_TOP and SB_BOTTOM request codes. The SB_TOP request code indicates that the user has reached the top value of the scrolling range. An application scrolls the window content downward so that the top of the data object is visible. The SB_BOTTOM request code indicates that the user has reached the bottom value of the scrolling range. If an application processes the SB_BOTTOM request code, it scrolls the window content upward so that the bottom of the data object is visible.

If you want a keyboard interface for a standard scroll bar, you can create one yourself by processing the WM_KEYDOWN message in your window procedure and then performing the appropriate scrolling action based on the virtual-key code that accompanies the message. For information about how to create a keyboard interface for a scroll bar, see Creating a Keyboard Interface for a Standard Scroll Bar.

Как добавлять скроллинг куда-угодно?

Давайте попробуем показать, как работают классы Canvas и Scrollbar вместе. Для этого создадим программу, которая будет загружать изображение, которое и изменяет размеры контейнера. После того, как нажать на кнопку «Загрузить изображения», она исчезает, а в элемент класса Canvas добавляется картинка, размер которой больше, чем у самого контейнера. В качестве такого изображения может использоваться любой графический файл.

Вот так будет выглядеть окно программы, если в нее будет загружено изображение.

Обратите внимание на скроллбары, которые появились после того, как был вставлен в окно логотип Python. 

Интерфейс скроллинга стандартный у виджета Canvas. Кроме этого, данный элемент обладает методом create_window(), который предусматривает, что файл будет располагаться в той же папке.

import tkinter as tk

class App(tk.Tk):

    def __init__(self):

        super().__init__()

        self.scroll_x = tk.Scrollbar(self, orient=tk.HORIZONTAL)

        self.scroll_y = tk.Scrollbar(self, orient=tk.VERTICAL)

        self.canvas = tk.Canvas(self, width=300, height=100,

                                xscrollcommand=self.scroll_x.set,

                                yscrollcommand=self.scroll_y.set)

        self.scroll_x.config(command=self.canvas.xview)

        self.scroll_y.config(command=self.canvas.yview)

        self.frame = tk.Frame(self.canvas)

        self.btn = tk.Button(self.frame, text=”Загрузить изображение”,

                             command=self.load_image)

        self.btn.pack()

        self.canvas.create_window((0, 0), window=self.frame,

                                  anchor=tk.N + tk.W)

        self.canvas.grid(row=0, column=0, sticky=”nswe”)

        self.scroll_x.grid(row=1, column=0, sticky=”we”)

        self.scroll_y.grid(row=0, column=1, sticky=”ns”)

        self.rowconfigure(0, weight=1)

        self.columnconfigure(0, weight=1)

        self.bind(“”, self.resize)

        self.update_idletasks()

        self.minsize(self.winfo_width(), self.winfo_height())

    def resize(self, event):

        region = self.canvas.bbox(tk.ALL)

        self.canvas.configure(scrollregion=region)

    def load_image(self):

        self.btn.destroy()

        self.image = tk.PhotoImage(file=”python.gif”)

        tk.Label(self.frame, image=self.image).pack()

if __name__ == “__main__”:

    app = App()

    app.mainloop()

Теперь давайте разбирать этот код подробно, шаг за шагом. Рассмотрим принципы работы скроллбаров в Tkinter, и разберемся, как сделать окно адаптивным в случае, если, например, изменяется его размер. 

Why not pseudos

Why not pseudo-elements?

Scrollbars are more like text-decoration, borders, outlines than they are things like ::before/::after, or ::first-letter or ::first-line.

Just as we don’t have separate pseudo-elements for ::text-underline ::text-overline ::text-strike-through, or different border or outline sides, it doesn’t make sense to have separate pseudos for scrollbars or scrollbar parts!

, a feature mistakenly exposed to the web, should not need to be implemented everywhere for interop.

The scrollbar pseudo-elements as a set are not a good idea:

  • OSs continuously evolve their scrollbar designs to provide better user experience, beyond the ability of any set of pseudo-elements to accurately model this over time.
  • MacOS and Ubuntu, both have quite different scrollbar structure than that on Windows. Having something like the scrollbar pseudo-elements specified may make it harder for browsers to have decent behavior on different platforms.
  • Different OSs having different scrollbar structure also means testing interop is harder, because you would need to take not only engines but also platforms into account.

Static Methods

Scrollbar.init()

Scrollbar.init(elem, options?): Scrollbar
Param Type Description
Element The DOM element that you want to initialize scrollbar to.
, optional Initial options, see section above.

Initializes a scrollbar on the given element and returns scrollbar instance:

const scrollbar = Scrollbar.init(document.body, {
  damping: 0.2,
});

Scrollbar.initAll()

Scrollbar.init(options?): Scrollbar
Param Type Description
, optional Initial options, see section above.

Automatically init scrollbar on all elements base on the selector , returns an array of scrollbars:

<div data-scrollbar> ... </div>

<article data-scrollbar> ... </article>
Scrollbar.initAll(); // 

Scrollbar.has()

Scrollbar.has(elem): boolean
Param Type Description
The DOM element that you want to check.

Checks if there is a scrollbar on given element:

Scrollbar.init(document.body);

Scrollbar.has(document.body); // true

Scrollbar.get()

Scrollbar.get(elem): Scrollbar
Param Type Description
The DOM element that you want to check.

Gets scrollbar on the given element. If no scrollbar instance exsits, returns :

const scrollbar = Scrollbar.init(document.body);

Scrollbar.get(document.body) === scrollbar; // true

Scrollbar.get(document.documentElement); // undefined

Scrollbar.getAll()

Scrollbar.getAll(): SmoothScrollbar

Returns an array that contains all scrollbar instances:

Scrollbar.getAll(); // 

Scrollbar.destroy()

Scrollbar.destroy(elem): void
Param Type Description
The DOM element that scrollbar is initialized to.

Removes scrollbar on the given element:

Scrollbar.init(document.body);
Scrollbar.has(document.body); // true

Scrollbar.destroy(document.body);
Scrollbar.has(document.body); // false
Scrollbar.destroyAll(): void

Removes all scrollbar instances from current document.

Scrollbar.use()

Scrollbar.use(...Plugins: ScrollbarPluginClass): void
Param Type Description
Scrollbar plugin class.

Attaches plugins to scrollbars. See Plugin System;

import Scrollbar, { ScrollbarPlugin } from 'smooth-scrollbar';
import OverscrollPlugin from 'smooth-scrollbar/plugin/overscroll';

class MyPlugin extends ScrollbarPlugin {
  ...
}

Scrollbar.use(MyPlugin, OverscrollPlugin);

Scrollbar.attachStyle()

Attaches default style sheets to current document. You don’t need to call this method manually unless you removed the default styles via ;

Элементы скроллбара

Вы можете управлять отдельными элементами для кастомизации скроллбара:

  • webkit-scrollbar — Все поле скроллбара.
  • webkit-scrollbar-button — Кнопки скрола вверх и вниз (зачастую имеет иконки в виде стрелок).
  • webkit-scrollbar-track — Трек поля по которому передвигается ползунок скролла.
  • webkit-scrollbar-track-piece — Свободное место на треке (которое не занято ползунком).
  • webkit-scrollbar-thumb — Сам ползунок.
  • webkit-scrollbar-corner — Угол на скроллбаре, на котором как правило пересекаются вертикальный и горизонтальный скроллбар.
  • webkit-resizer — Если ваш скроллбар поддерживает изменение размера поля к которому он прикреплен, можете кастомизировать этот элемент.

#

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

Элемент управления ScrollBar

UserForm.ScrollBar – это элемент управления пользовательской формы, представляющий из себя полосу прокрутки с кнопками, реагирующий как на перемещение ползунка, так и на нажатие кнопок.

Элемент управления ScrollBar предназначен в VBA Excel для ввода пользователем числовых данных, которые ограничены минимальным и максимальным значениями. Увеличение или уменьшение значения полосы прокрутки осуществляется с указанным шагом при помощи ползунка или кнопок.

Визуально, элемент управления ScrollBar состоит из полосы прокрутки и двух кнопок, работающих аналогично кнопкам элемента управления SpinButton. Ориентация может быть горизонтальной или вертикальной в зависимости от настроек.

Полоса прокрутки в VBA Excel используется в паре с элементом управления TextBox или Label. Вспомогательный элемент необходим, чтобы отобразить текущее значение ScrollBar на пользовательской форме.

Scroll Bar Requests

The user makes scrolling requests by clicking various parts of a scroll bar. The system sends the request to the specified window in the form of a WM_HSCROLL or WM_VSCROLL message. A horizontal scroll bar sends the WM_HSCROLL message; a vertical scroll bar sends the WM_VSCROLL message. Each message includes a request code that corresponds to the user’s action, to the handle to the scroll bar (scroll bar controls only), and, in some cases, to the position of the scroll box.

The following diagram shows the request code that the user generates when clicking various parts of a scroll bar.

The SB_ values specify the action the user takes. An application examines the codes that accompany the WM_HSCROLL and WM_VSCROLL messages and then performs the appropriate scrolling operation. In the following table, the user’s action is specified for each value, followed by the application’s response. In each case, a unit is defined by the application as appropriate for the data. For example, the typical unit for scrolling text vertically is a line of text.

Request Action Response
SB_LINEUP The user clicks the top scroll arrow. Decrements the scroll box position; scrolls toward the top of the data by one unit.
SB_LINEDOWN The user clicks the bottom scroll arrow. Increments the scroll box position; scrolls toward the bottom of the data by one unit.
SB_LINELEFT The user clicks the left scroll arrow. Decrements the scroll box position; scrolls toward the left end of the data by one unit.
SB_LINERIGHT The user clicks the right scroll arrow. Increments the scroll box position; scrolls toward the right end of the data by one unit.
SB_PAGEUP The user clicks the scroll bar shaft above the scroll box. Decrements the scroll box position by the number of data units in the window; scrolls toward the top of the data by the same number of units.
SB_PAGEDOWN The user clicks the scroll bar shaft below the scroll box. Increments the scroll box position by the number of data units in the window; scrolls toward the bottom of the data by the same number of units.
SB_PAGELEFT The user clicks the scroll bar shaft to the left of the scroll box. Decrements the scroll box position by the number of data units in the window; scrolls toward the left end of the data by the same number of units.
SB_PAGERIGHT The user clicks the scroll bar shaft to the right of the scroll box. Increments the scroll box position by the number of data units in the window; scrolls toward the right end of the data by the same number of units.
SB_THUMBPOSITION The user releases the scroll box after dragging it. Sets the scroll box to the position specified in the message; scrolls the data by the same number of units the scroll box has moved.
SB_THUMBTRACK The user drags the scroll box. Sets the scroll box to the position specified in the message and scrolls the data by the same number of units the scroll box has moved for applications that draw data quickly. Applications that cannot draw data quickly must wait for the SB_THUMBPOSITION request code before moving the scroll box and scrolling the data.
SB_ENDSCROLL The user releases the mouse after holding it on an arrow or in the scroll bar shaft. No response is needed.

A scroll bar generates SB_THUMBPOSITION and SB_THUMBTRACK request code when the user clicks and drags the scroll box. An application should be programmed to process either the SB_THUMBTRACK or SB_THUMBPOSITION request code.

The SB_THUMBPOSITION request code occurs when the user releases the mouse button after clicking the scroll box. An application that processes this message performs the scrolling operation after the user has dragged the scroll box to the desired position and released the mouse button.

The SB_THUMBTRACK request code occurs as the user drags the scroll box. If an application processes SB_THUMBTRACK request codes, it can scroll the content of a window as the user drags the scroll box. However, a scroll bar can generate many SB_THUMBTRACK request code in a short period, so an application should process these request codes only if it can quickly repaint the content of the window.

Standard Scroll Bars and Scroll Bar Controls

A scroll bar is included in a window either as a standard scroll bar or as a scroll bar control. A standard scroll bar is located in the nonclient area of a window. It is created with the window and displayed when the window is displayed. The sole purpose of a standard scroll bar is to enable the user to generate scrolling requests for viewing the entire content of the client area. You can include a standard scroll bar in a window by specifying WS_HSCROLL, WS_VSCROLL, or both styles when you create the window. The WS_HSCROLL style creates a horizontal scroll bar positioned at the bottom of the client area. The WS_VSCROLL style creates a vertical scroll bar positioned at the right of the client area. The SM_CXHSCROLL and SM_CYHSCROLL system metric values define the width and height of a standard horizontal scroll bar. The SM_CXVSCROLL and SM_CYVSCROLL values define the width and height of a standard vertical scroll bar. A standard scroll bar is part of its associated window and therefore does not have a window handle of its own.

A scroll bar control is a control window that belongs to the SCROLLBAR window class. A scroll bar control appears and functions like a standard scroll bar, but it is a separate window. As a separate window, a scroll bar control takes direct input focus. Unlike a standard scroll bar, a scroll bar control also has a built-in keyboard interface.

You can use as many scroll bar controls as needed in a single window. When you create a scroll bar control, you must specify the scroll bar’s size and position. However, if a scroll bar control’s window can be resized, adjustments to the scroll bar’s size must be made whenever the size of the window changes.

The advantage of using a standard scroll bar is that the system creates the scroll bar and automatically sets its size and position. However, standard scroll bars are sometimes too restrictive. For example, suppose that you want to divide a client area into quadrants and use a separate set of scroll bars to control the content of each quadrant. You cannot use standard scroll bars because you can only create one set of scroll bars for a particular window. Use scroll bar controls instead, because you can add as many of them to a window as you want.

Applications can provide scroll bar controls for purposes other than scrolling the content of a window. For example, a screen saver application might provide a scroll bar for setting the speed at which graphics are moved about on the screen.

A scroll bar control can have a number of styles that serves to control the orientation and position of the scroll bar. You specify the styles that you want when you call the CreateWindowEx function to create a scroll bar control. Some of the styles create a scroll bar control that uses a default width or height. However, you must always specify the x- and y-coordinates and the other dimensions of the scroll bar.

For a table of scroll bar control styles, see Scroll Bar Control Styles.

Note

To use visual styles with scroll bars, an application must include a manifest and must call InitCommonControls at the beginning of the program. For information on visual styles, see Visual Styles. For information on manifests, see Enabling Visual Styles.

How to Create Custom Scrollbars with CSS

With our setup out of the way, we can jump into the fun part of the tutorial. The first part of this section will be learning the various CSS properties available to use for styling.

In the second part we’ll implement four different types of scrollbars to give you some ideas for making your own scrollbars.

Unfortunately we still don’t have any standardized cross-browser support for styling scrollbars with CSS. Firefox and Webkit-based browsers like Chrome, Edge, and Safari have different properties for styling.

This tutorial will mainly focus on Webkit browsers, because they offer more options for styling, but we will briefly cover Firefox as well.

  • – the entire scrollbar
  • – the entire progress bar area of the scrollbar
  • – the draggable section of the scrollbar

The below properties are available but are less commonly used:

  • – the up/down buttons at each end of the scrollbar
  • – part of scrollbar not covered by the thumb
  • – bottom corner where horizontal and vertical scrollbars meet

There are currently two available CSS properties for styling scrollbars in Firefox

  • – controls width of scrollbar, with only two options available being or
  • – takes two colors which are used for the coloring of the thumb and track of the scrollbar in that order

Now that you know your options for customizing scrollbars, let’s put it into practice with some examples.

Dark theme websites are all the rage right now. Sticking with the default browser scrollbar could come off as jarring to users because it doesn’t fit all that well with a dark themed website.

Let’s use our newfound knowledge of CSS to create a dark theme scrollbar with a rounded border inspired by CSS Tricks’ website:

The result is a little hard to see in the screenshot, but the track is black and the thumb is a darkish gray color.

For this example you’ll be making a minimalist scrollbar. This type of scrollbar would work well if you are going for a simple, elegant style for your website.

The most important thing to note is that you have the ability to use and pseudo-elements from CSS to further style your scrollbar. In this case the scrollbar will turn a darker gray when you hover and drag on the thumb.

The result:

In this section, the focus is on using a repeating linear gradient to create a pattern effect on our scrollbar track. The same could be done for the scrollbar thumb as well.

Another thing to notice is that you can style the scrollbar thumb with a border, which you can use to create a number of cool effects. In this case I made the background color of the thumb transparent so that you can see the scrollbar track pattern as we scroll.

The result:

This example uses a linear gradient and a trick with box shadow to make it look like the scrollbar is changing color as you move up and down the page. What’s really happening is that the background of the scrollbar track is being revealed beneath the thumb.

It works because the box-shadow takes up all the space of the scrollbar except for where the thumb is. Because the thumb is transparent the gradient color of the background shows through.

The result:

Альтернативные конструкции

Было предложено или реализовано множество вариантов традиционного дизайна и использования полосы прокрутки. Чтобы избежать ограничения видимости окна полосами прокрутки при сохранении функциональности, было предложено использовать программный трос (тонкая линия), связанный с перемещением указателя мыши по тросу. Точно так же полосу прокрутки можно разместить непосредственно внутри содержимого, где она будет полезна, как для уменьшения используемого пространства, так и для уменьшения необходимых перемещений указателя.

Включение визуальных и рабочих подсказок в область отображения полосы прокрутки может указать, какие направления позволяют прокручивать движение, а также какие взаимодействия с полосой прокрутки доступны. Это может быть пустое поле, сигнализирующее об окончании списка, отключении кнопок прокрутки и изменении цвета полосы прокрутки.

Некоторые полосы прокрутки включают в себя визуальный индикатор положения, который помогает определить, где действие прокрутки прошло или будет перемещаться в содержимом. Для многостраничного контента индикатор текущего номера страницы по сравнению с общим номером страницы может быть включен рядом с ползунком при прокрутке, а более широкие полосы прокрутки могут включать обзор всей страницы. В полосах прокрутки, подобных тем, которые используются в телефонных списках контактов, состоящих из букв алфавита, буква, соответствующая текущей области, может быть увеличена или выделена каким-либо образом. Хотя они стабильны и предоставляются приложением, некоторые приложения и поисковые системы позволяют использовать маркеры релевантности, предоставленные или добавленные пользователем. Они могут быть строго визуальными или могут автоматически останавливать действие на полосе прокрутки при достижении каждого маркера. Они могут быть подчеркнуты цветом или даже звуком, чтобы дополнительно помочь пользователю найти то, что ему нужно в контенте.

Use-cases

Use-case for color and/or width modification of scrollbars.

Dark colored webapp designs

Dark colored web app designs are particularly sensitive to the visual noise created from the intrusively high-contrast default platform scrollbars.

TweetDeck

Note that TweetDeck appears to only use three colors (but setting on multiple properties)

  • scrollbar-face-color: #e1e8ed;
  • scrollbar-track-color: #F5F8FA;
  • scrollbar-arrow-color: #292f33;

Webflow Designer

Sites blocking browsers

Some sites have designs that depend on scrollbar styling (specifically colors) so much that they block browsers that do not have such a feature:

https://webcompat.com/issues/8030

Google uses scrollbar width modification in Gmail and Google Docs portions, typically in narrower areas where a smaller scrollbar helps to show more content.

Subtler cleaner web app UI

Tab Atkins’s personal blog authoring web UI has a much narrower than default scrollbar to help reduce distraction and visual noise while writing a blog post.

Browser UI

Some browser(s) build UI using web platform features, sometimes adding internal only extensions. Ideally the a web platform features can be re-used, however if a new feature is needed for such UI, it does not mean it should also be added to features exposed to the web. Such internal-only extensions can be used as prototypes for experience.

Анимация листьев

1. Ключевые кадры

Давайте для начала выясним, как устроена анимация, и какие CSS-свойства нужны, чтобы её создать.

Для объявления анимации и задания ключевых кадров используется правило , после которого указывается название анимации. С помощью ключевых кадров можно задать нужное поведение для элементов на любом этапе. Кадры можно задавать в процентах: например, — это начало анимации, — её конец. Это не единственный способ — можно воспользоваться ключевыми словами и , но проценты позволяют задать любое промежуточное состояние. Код нашей анимации:

Что здесь происходит? Свойство мы уже применяли ранее, но теперь используем функцию , которая позволяет изменять масштаб элемента. В начале анимации масштаб нулевой (параметр ), а затем он должен увеличиться до обычного масштаба (параметр ). И это именно то, что нужно, чтобы имитировать плавный рост наших листьев.

2. Анимирование элементов: теория

Хорошо, мы создали анимацию, а теперь нам нужно её применить к конкретным элементам. Для этого понадобятся несколько CSS-свойств:

  • — название анимации. Мы уже задавали название при создании анимации с помощью , именно его и нужно указать.
  • — длительность анимации. Измеряется в секундах или миллисекундах.
  • — задержка анимации. Свойство позволяет установить время между тем моментом, когда анимация была присвоена элементу, и непосредственно началом анимации.
  • — состояние элемента до и после анимации. С помощью этого свойства можно контролировать, как будет себя вести элемент до начала анимации и после её завершения. У свойства есть несколько значений.

Это только некоторые свойства, которые понадобятся нам сейчас, но есть и другие. Познакомиться с остальными можно, изучив MDN или курс по анимации.

3. Анимирование элементов: практика

Теперь мы знаем что делать — нужно задать созданную ранее анимацию листочкам, и они начнут расти. Для этого укажем название анимации и её длительность.

Но для чего мы задали значение свойству ? По умолчанию после окончания анимации элементы возвращаются в исходное состояние, а в данном случае нам это не нужно. Мы хотим, чтобы исходное состояние анимации было как в первом ключевом кадре (), а финальное состояние — как в последнем ().

Кроме самой анимации в этом фрагменте кода мы задаём положение листков относительно родительского элемента и точку применения трансформации с помощью уже знакомого свойства . По умолчанию листки росли бы в центральной точке и увеличивались равномерно во все стороны. Но тогда в начале анимации они бы повисли в воздухе рядом с веткой, что не очень реалистично, поэтому мы переопределили это поведение и заставили их расти от начала ветки.

Возможно, вы обратили внимание, что мы анимировали только нечётные элементы. Для анимации остальных нам понадобится добавить поворот на 90 градусов, чтобы листки росли с обеих сторон ветки

Получается, чётные будут направлены в одну сторону, а нечётные — в другую.

Мы создали ещё одну анимацию, теперь чётные элементы будут увеличиваться в размере также, как и нечётные, но плюс к этому они с самого начала анимации будут повёрнуты под нужным углом.

Остался последних штрих — добавим задержку анимации для каждого ряда листьев, чтобы они появлялись не одновременно, а по очереди. Вот эти три листка появятся на концах веток и будут последними, так как у них самая большая задержка. Для всех остальных задержка будет уменьшаться с шагом :

Ура-ура, дерево готово!

Весь код анимации, который мы написали в этом туториале, доступен на CodePen.

See the Pen
tree by sasha_htmlacademy (@sasha-sm)
on CodePen.

Исследования

В отчете Уильяма Бакстона и Брэда Майерса за 1986 год были протестированы различные способы взаимодействия двумя руками, включая прокрутку, щелчок и изменение размера. В их исследовании щелчок и изменение размера выполнялись параллельно. В первом эксперименте участникам предлагалось выполнить задачу выбора / позиционирования, а во втором эксперименте участникам предлагалось выполнить сложную задачу навигации / выбора. Исследование показало, что пользователи могут выполнять эти задачи быстрее и параллельно, когда они используют обе руки, но не обязательно, когда они используют обе руки одновременно. Они также обнаружили, что чем более взаимосвязанными были задачи, которые пользователь выполнял каждой рукой, тем быстрее они выполняли задачи, которые их просили выполнить.

Goals & Features

  • A simple, powerful and good documented API.
  • High browser compatibility (IE8+, Safari6+, Firefox, Opera, Chrome and Edge).
  • Usage of the most recent technologies to ensure maximum efficiency and performance on newer browsers.
  • Can be used without any dependencies or with jQuery.
  • Automatic update detection — after the initialization you don’t have to worry about updating.
  • Extremely powerful scroll method with features like animations, relative coordinates, scrollIntoView and more.
  • Mouse and touch support.
  • Textarea and Body support.
  • RTL Direction support. (with normalization)
  • Simple and effective scrollbar-styling.
  • Rich extension system.
  • TypeScript support.
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *