The OpenNET Project / Index page

[ новости /+++ | форум | теги | ]



Индекс форумов
Составление сообщения

Исходное сообщение
"Раздел полезных советов: Как автоматически отключить закрепл..."
Отправлено auto_tips, 11-Май-18 11:18 
Последнее время дизайнеры всё чаще используют CSS-свойство "position: fixed" для закрепления шапки и футера, что создаёт дискомфорт при просмотре страниц и съедает драгоценное экранное пространство на широкоформатных экранах.

Для автоматического отключения "position: fixed"  можно использовать дополнение [[https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/ greasemonkey]]
вместе с [[https://gist.github.com/vbuaraujo/bddb3b93a0b2b7e28e1b простым скриптом]]  unfix-all-the-toolbars.user.js:


   // ==UserScript==
   // @name        unfix-all-the-toolbars
   // @description Removes "position: fixed" style from elements, unfixing "toolbars" and the such.
   // @namespace   http://inf.ufrgs.br/~vbuaraujo/
   // @include     *
   // @version     1
   // @grant       none
   // ==/UserScript==


   /*
   Based on https://stackoverflow.com/questions/13696100/greasemonkey-sc...
   2015-02-17: Original version.
   2016-05-01: Added the styleWidth threshold heuristic.
   The big problem here is we want to avoid unfixing *all* "position: fixed"
   elements, because some of them are fake popup windows which become quite
   unusable if you change them to "position: static". So we need some heuristic
   to distinguish "legitimate" fixed elements from gratuitous ones like navbars.
   */

   function numPixels(str) {
     if (str.endsWith("px"))
       return Number(str.slice(0, -2));
     else {
       console.log("unfix-all-the-toolbars: Computed width is not in pixels! " + width);
       return null;
     }
   }

  function unfixAll() {
     var bodyStyle = window.getComputedStyle(document.body);
     var pageWidth = numPixels(bodyStyle.width);
     var pageHeight= numPixels(bodyStyle.height);
     var toolbarWidthThreshold = 0.8 * pageWidth;
  
     Array.forEach(
       /* Assorted selection of likely fixed elements, to avoid querying all elements */
       document.querySelectorAll("h1, h2, ul, ol, li, div, nav, header, footer"),
       function (el) {
         var style = window.getComputedStyle(el);
         if (style.position === "fixed") {
           /* Avoid unfixing JavaScript popus like Twitter's "confirm retweet" window */
           if (style.display === "none" || style.visibility === "hidden") return;
           if (numPixels(style.width) < toolbarWidthThreshold) return;
        
           // Try to select the best replacement for 'fixed'. Still breaks lots of things, though.
          if (numPixels(style.bottom) === 0 && numPixels(style.top) > 0)
             el.style.position = "static";    // Use static for footers.
           else
             el.style.position = "absolute";
         }
      });
   }

   window.addEventListener("load", unfixAll);

Другим вариантом может стать Firefox-дополнение [[https://addons.mozilla.org/en-US/firefox/addon/unstickall/ unstickall]], которое позволяет отключить закрепление любого блока через клик на нём.


URL:
Обсуждается: http://www.opennet.ru/tips/info/3064.shtml

 

Ваше сообщение
Имя*:
EMail:
Для отправки ответов на email укажите знак ! перед адресом, например, !user@host.ru (!! - не показывать email).
Более тонкая настройка отправки ответов производится в профиле зарегистрированного участника форума.
Заголовок*:
Сообщение*:
 
При общении не допускается: неуважительное отношение к собеседнику, хамство, унизительное обращение, ненормативная лексика, переход на личности, агрессивное поведение, обесценивание собеседника, провоцирование флейма голословными и заведомо ложными заявлениями. Не отвечайте на сообщения, явно нарушающие правила - удаляются не только сами нарушения, но и все ответы на них. Лог модерирования.



Партнёры:
PostgresPro
Inferno Solutions
Hosting by Hoster.ru
Хостинг:

Закладки на сайте
Проследить за страницей
Created 1996-2024 by Maxim Chirkov
Добавить, Поддержать, Вебмастеру