Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name b3d slider test
- // @namespace http://andreymal.org/tabun/userscripts
- // @include http://b3d.org.ua/forum/
- // @include http://b3d.org.ua/forum/index.php
- // @version 1
- // @grant none
- // ==/UserScript==
- 'use strict';
- // TODO: это, очевидно, должно быть в css-файле :)
- var styles = [
- '.ekSliderBlock {',
- ' position: relative;',
- '}',
- '.ekSliderList {',
- ' color: white;',
- ' position: absolute;',
- ' top: 0px;',
- ' left: 0px;',
- ' transition-property: left;',
- ' transition-timing-function: ease;',
- '}',
- '.ekSliderList a, .ekSliderList a:visited, .ekSliderList a:hover {',
- ' color: inherit;',
- ' text-decoration: none;',
- '}',
- '.ekSliderLink, .ekSliderLink:visited {',
- ' display: inline-block;',
- ' background-color: white;',
- ' background-position: center center;',
- ' background-size: cover;',
- ' margin: 0;',
- ' padding: 0;',
- ' position: relative;',
- ' vertical-align: top;',
- '}',
- '.ekSliderInfo {',
- ' padding: 10px;',
- ' box-sizing: border-box;',
- ' margin: 0 auto;',
- ' width: 90%;',
- ' margin-top: 20px;',
- ' background-color: rgba(0, 100, 76, 0.4);',
- ' border-radius: 5px;',
- ' border-spacing: 0px;',
- '}',
- '.ekSliderInfo hr {',
- ' border: 0;',
- ' height: 1px;',
- ' background-image: linear-gradient(to right, rgba(250, 250, 250, 0), rgba(250, 250, 250, 0.75), rgba(250, 250, 250, 0));',
- '}',
- '.ekSliderAuthor {',
- ' position: absolute;',
- ' bottom: 10%;',
- ' right: 5%;',
- ' color: black;',
- ' display: block;',
- ' text-shadow: 0 0 1px rgba(255, 255, 255, 0.9);',
- '}',
- '.ekSliderBlock .ekSliderNavigate {',
- ' top: 90%;',
- ' display: block;',
- ' text-align: center;',
- ' /* Остальное родное */',
- '}',
- '.ekSliderBlock .ekSliderNavigate span {',
- ' float: none;',
- ' display: inline-block;',
- '}'
- ];
- var s = document.createElement('style');
- s.textContent = styles.join('\n');
- document.head.appendChild(s);
- s = null;
- var EKSlider = function(container) {
- this.container = container;
- this.animDuration = 500;
- // TODO: поменять это на идеологически верный dataset
- this.scrollDelay = parseInt(container.getAttribute('scrolldelay'));
- this.size = parseInt(container.getAttribute('width'));
- this.currentItem = null; // Текущий отображаемый элемент
- this.itemsCount = 0; // Общее число элементов
- this.listElem = null; // DOM-контейнер с элементами
- this.navElem = null; // DOM-контейнер с кнопками-переключалкам элементов
- this.changeIntervalId = null; // ID таймера, прокручивающего элементы
- this.paused = false; // Приостановлен ли таймер, переключающий элементы
- this._overEventCurrent = null;
- this._outEventCurrent = null;
- // Загружаем данные и запускаем слайдер
- var x = new XMLHttpRequest();
- x.open('POST', this.container.getAttribute('getfrom'));
- x.onload = function() {
- this.start(JSON.parse(x.responseText));
- }.bind(this);
- x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- x.send('forSlider=1');
- };
- EKSlider.prototype.start = function(data) {
- // При наведении мыши приостанавлимаем автоматическую прокрутку
- this._overEventCurrent = this._mouseOverEvent.bind(this);
- this._outEventCurrent = this._mouseOutEvent.bind(this);
- this.container.addEventListener('mouseover', this._overEventCurrent);
- this.container.addEventListener('mouseout', this._outEventCurrent);
- // Контейнер для блоков конкурса
- var list = document.createElement('div');
- list.className = 'ekSliderList';
- list.style.width = (this.size * this.itemsCount) + 'px';
- list.style.transitionDuration = this.animDuration + 'ms';
- this.listElem = list;
- // Кнопочки навигации
- var nav = document.createElement('div');
- nav.className = 'ekSliderNavigate';
- nav.addEventListener('click', this._btnClickEvent.bind(this));
- this.navElem = nav;
- data.forEach(this.addItem.bind(this)); // Добавляем элементы
- this.container.appendChild(list);
- this.container.appendChild(nav);
- this.changeIntervalId = setInterval(this.next.bind(this), this.scrollDelay + this.animDuration);
- };
- EKSlider.prototype.addItem = function(item) {
- // В ссылку кладём всё
- var elem = document.createElement('a');
- elem.className = 'ekSliderLink';
- elem.style.width = this.size + 'px';
- elem.style.height = this.size + 'px';
- elem.style.backgroundImage = 'url("' + item[2] + '")';
- elem.href = item[0];
- // Верхний блок с информацией
- var infoBlock = document.createElement('div');
- infoBlock.className = 'ekSliderInfo';
- // Название конкурса
- var title = document.createElement('strong');
- title.textContent = item[1];
- // Текущая тема конкурса
- var theme = document.createElement('p');
- var em = document.createElement('em');
- em.textContent = 'Прием работ на тему: «' + item[3] + '»';
- theme.appendChild(em);
- // Автор работы на фоне
- var author = document.createElement('em');
- author.className = 'ekSliderAuthor';
- author.textContent = item[4];
- infoBlock.appendChild(title);
- infoBlock.appendChild(document.createElement('hr'));
- infoBlock.appendChild(theme);
- elem.appendChild(infoBlock);
- elem.appendChild(author);
- this.listElem.appendChild(elem);
- // Кнопочка с навигацией
- var btn = document.createElement('span');
- btn.dataset.item = this.itemsCount;
- this.navElem.appendChild(btn);
- // Проверяем счётчик
- if (this.itemsCount === 0) {
- this.currentItem = 0;
- // TODO: поменять на btn.classList.add('shown');
- btn.setAttribute('shown', 'true');
- }
- this.itemsCount++;
- // Корректируем длину контейнера
- this.listElem.style.width = (this.itemsCount * this.size) + 'px';
- };
- EKSlider.prototype.next = function() {
- if (!this.paused) {
- this.set(this.currentItem >= (this.itemsCount - 1) ? 0 : this.currentItem + 1);
- }
- };
- EKSlider.prototype.set = function(i) {
- if (i < 0 || i >= this.itemsCount) {
- return false;
- }
- if (this.currentItem === i) {
- return true;
- }
- // TODO: поменять на this.navElem.children[this.currentItem].classList.remove('shown');
- this.navElem.children[this.currentItem].removeAttribute('shown');
- this.currentItem = i;
- // TODO: поменять на this.navElem.children[this.currentItem].classList.add('shown');
- this.navElem.children[this.currentItem].setAttribute('shown', 'true');
- this.listElem.style.left = (-this.size * this.currentItem) + 'px';
- return true;
- };
- EKSlider.prototype.destroy = function() {
- if (this.changeIntervalId !== null) {
- clearInterval(this.changeIntervalId);
- this.changeIntervalId = null;
- }
- if (this.listElem !== null) {
- (this.listElem.parentNode || this.listElem.parentElement).removeChild(this.listElem);
- this.listElem = null;
- }
- if (this.navElem !== null) {
- (this.navElem.parentNode || this.navElem.parentElement).removeChild(this.navElem);
- this.navElem = null;
- }
- this.itemsCount = 0;
- this.currentItem = null;
- this.paused = true;
- this.container.removeEventListener('mouseover', this._overEventCurrent);
- this.container.removeEventListener('mouseout', this._outEventCurrent);
- this._overEventCurrent = null;
- this._outEventCurrent = null;
- };
- EKSlider.prototype._btnClickEvent = function(event) {
- var i = (event.target || event.srcElement).dataset.item;
- if (!i) {
- return true;
- }
- this.set(parseInt(i));
- return false;
- };
- EKSlider.prototype._mouseOverEvent = function() {
- this.paused = true;
- };
- EKSlider.prototype._mouseOutEvent = function() {
- this.paused = false;
- };
- // TODO: поменять load на DOMContentLoaded
- window.addEventListener('load', function() {
- window.ekSlider = new EKSlider(document.querySelector('.ekSliderBlock'));
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement