Перейти до вмісту
Пошук в
  • Детальніше...
Шукати результати, які ...
Шукати результати в ...

ArtemPitov

Користувачі
  • Публікації

    4 389
  • З нами

  • Відвідування

Записи блогу, опубліковані користувачем ArtemPitov

  1. ArtemPitov
    Написал маленький плагин для скрытия текста, может кому пригодится.   Настройки 
    data-length="100" - длина, включая пробелы и html теги | default: 100 data-text_show="Показать еще" - текст кнопки data-text_hide="Скрыть" - текст кнопки  
    Использование 
    <div class="Htext" data-length="250" data-text_show="Показать еще" data-text_hide="Скрыть"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> Сам плагин 
     
     
  2. ArtemPitov
    Интересная статейка, особенно тех кто думает что СЕО это магия, а оптимизация только для одаренных ...

    Скорость загрузки мобильных страниц будет влиять на их рейтинг в поиске
    Обновление о скорости загрузки мобильных страниц вступает в силу для всех пользователей.
     
    Google уже учитывает этот критерий при ранжировании веб-страниц, но только предназначенных для обычных компьютеров.
    С июля 2018 г. позиция мобильного сайта в результатах поиска также будет зависеть от того, с какой скоростью он загружается. Мы ожидаем, что это нововведение повлияет на результаты по незначительному количеству запросов и затронет только самые медленные сайты. Наш новый критерий будет одинаково применяться к любым веб-страницам независимо от того, на какой технологии они основаны. Поскольку для Google очень важен смысл поискового запроса, медленные страницы по-прежнему будут занимать высокие позиции, если содержат интересный и релевантный контент. Мы настоятельно рекомендуем разработчикам уже сейчас задуматься над тем, как скорость загрузки и многие другие факторы влияют на удобство сайта. У нас нет инструмента, который позволит однозначно сказать, изменится ли позиция ваших веб-страниц в результатах поиска, но вам могут помочь перечисленные ниже ресурсы.
       
    Отчет об удобстве пользования браузером Chrome – это общедоступный свод данных о показателях посещаемых сайтов, определяющих удобство их использования в браузере Chrome.     Lighthouse  представляет собой автоматизированное решение, которое входит в состав Инструментов разработчика Chrome. Оно помогает оценивать качество веб-страниц по различным критериям, таким как скорость загрузки и удобство для людей с ограниченными возможностями.     PageSpeed Insights – это инструмент, который позволяет узнать, какие результаты продемонстрирует страница в отчете об удобстве пользования браузером Chrome, и предлагает варианты оптимизации.  
    Оригинал https://webmaster-ru.googleblog.com/2018/04/skorost-zagruzki-vlijaet-na-reiting-v-poiske.html 
  3. ArtemPitov
    Простая реализация подсказки внутри input-a
     
    Demo
    Название  
    HTML
    <div class="inputer"> <label>Название</label> <input type="text" name=""> </div> CSS
    .inputer { border: 1px solid #ddd; position: relative; display: block; width: 100%; max-width: 350px; border-radius: 4px; overflow: hidden; } .inputer label { position: absolute; top: 40%; left: 5px; opacity: 0; transition: all .1s linear; visibility: hidden; font-size: 12px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .inputer label, .inputer input::placeholder { color: #777; font-weight: bold; opacity: .8; } .inputer.active label { opacity: 1; top: 2px; visibility: visible; font-size: 11px; opacity: .8; } .inputer.active input { padding: 16px 5px 2px !important; } .inputer input, .inputer input:hover, .inputer input:focus, .inputer input:active { box-shadow: none; outline: none; border:none; border-radius: 0; display: block; width: 100%; padding: 9px 5px; font-size: 12px; } JS
    let inputerFn = (el) => { let $el = $(el); $el.parent().toggleClass('active', $el.val().length > 0); }; $('.inputer input').each(function (idx, el) { let $el = $(el); $el.attr('placeholder', $el.siblings('label').text()); inputerFn(el); }).on('input', function () { inputerFn(this); });  
    .inputer { border: 1px solid #ddd; position: relative; display: block; width: 100%; max-width: 350px; border-radius: 4px; overflow: hidden; } .inputer label { position: absolute; top: 40%; left: 5px; opacity: 0; transition: all .1s linear; visibility: hidden; font-size: 12px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .inputer label, .inputer input::placeholder { color: #777; font-weight: bold; opacity: .8; } .inputer.active label { opacity: 1; top: 2px; visibility: visible; font-size: 11px; opacity: .8; } .inputer.active input { padding: 16px 5px 2px !important; } .inputer input, .inputer input:hover, .inputer input:focus, .inputer input:active { box-shadow: none; outline: none; border:none; border-radius: 0; display: block; width: 100%; padding: 9px 5px; font-size: 12px; }
  4. ArtemPitov
    Простой вариант реализация гетера
     
    Для начала упаковываем все нужные данные в переменную  
    $data['data'] = .... Дальше берем div и делаем следующее 
    <div id="var" class="hidden" data-var="<?= base64_encode(json_encode($data)); ?>"></div> Потом пишем "проксю" на jquery
    let data = JSON.parse(window.atob($("#var").data('var'))); let proxy = new Proxy({}, { get(target, name) { return typeof data[name] !== undefined ? data[name] : false; } }); Используем, к примеру у нас в наборе есть токен
    proxy.token  
  5. ArtemPitov
    JS
    class APLazy { constructor (lazyClass) { if (typeof lazyClass === 'undefined') { this.lazyClass = 'APLazy'; } else { this.lazyClass = lazyClass; } this.lazyArray = []; } setLazy() { this.lazyArray = document.getElementsByClassName(this.lazyClass); } cleanLazy() { this.lazyArray = Array.prototype.filter.call(this.lazyArray, (l) => l.getAttribute('data-src')); } lazyLoad() { for (let element of this.lazyArray) { if (this.isInViewport(element)) { if (element.getAttribute('data-src')) { element.src = element.getAttribute('data-src'); element.removeAttribute('data-src'); } } } this.cleanLazy(); } isInViewport(element) { var rect = element.getBoundingClientRect(); return ( rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth) ); } registerListener(event, func) { if (window.addEventListener) { window.addEventListener(event, func); } else { window.attachEvent('on' + event, func); } } }  
    Используем JS
    if (typeof window.APLazy == 'undefined') { window.APLazy = new APLlazy('my-lazy-class'); window.APLazy.setLazy(); window.APLazy.lazyLoad(); window.APLazy.registerListener('scroll', function () { window.APLazy.lazyLoad(); }); window.APLazy.registerListener('resize', function () { window.APLazy.lazyLoad(); }); } else if (typeof window.APLazy == 'object' ) { window.APLazy.setLazy(); window.APLazy.lazyLoad(); }  
    Используем HTML 
    <img src="loader.gif" data-src="image.jpg" class="APLazy" />  
  6. ArtemPitov
    Давно все жалуются что при ошибках MySQL получаем пароли, набросал вот такую обертку, не претендую на уникальность, если у Вас есть замечания или предложения, всегда welcom =) 
     
    mysqli.php
    <?php namespace DB; final class MySQLi { private $connection; public function __construct( $hostname, $username, $password, $database, $port = '3306' ) { try { \mysqli_report( MYSQLI_REPORT_STRICT ); $this->connection = new \mysqli( $hostname, $username, $password, $database, $port ); $this->connection->set_charset( "utf8" ); $this->connection->query( "SET SQL_MODE = ''" ); } catch ( \mysqli_sql_exception $e ) { if ( \defined( 'IS_DEV' ) && IS_DEV ) { throw $e; } } } public function query( $sql ) { try { if ( !\is_null($this->connection) ) { $query = $this->connection->query( $sql ); } } catch ( \mysqli_sql_exception $e ) { if ( \defined( 'IS_DEV' ) && IS_DEV ) { throw $e; } } if ( !\is_null($this->connection) && !$this->connection->errno ) { if ( $query instanceof \mysqli_result ) { $data = array(); while ( $row = $query->fetch_assoc() ) { $data[] = $row; } $result = new \stdClass(); $result->num_rows = $query->num_rows; $result->row = isset($data[0]) ? $data[0] : array(); $result->rows = $data; $query->close(); return $result; } return true; } } public function escape($value) { if ( !\is_null($this->connection) ) { return $this->connection->real_escape_string($value); } return false; } public function countAffected() { if ( !\is_null($this->connection) ) { return $this->connection->affected_rows; } return false; } public function getLastId() { if ( !\is_null($this->connection) ) { return $this->connection->insert_id; } return false; } public function connected() { if ( !\is_null($this->connection) ) { return $this->connection->ping(); } return false; } public function __destruct() { if ( !\is_null($this->connection) ) { $this->connection->close(); } } }  

×
×
  • Створити...

Important Information

На нашому сайті використовуються файли cookie і відбувається обробка деяких персональних даних користувачів, щоб поліпшити користувальницький інтерфейс. Щоб дізнатися для чого і які персональні дані ми обробляємо перейдіть за посиланням . Якщо Ви натиснете «Я даю згоду», це означає, що Ви розумієте і приймаєте всі умови, зазначені в цьому Повідомленні про конфіденційність.