Javascript div во весь экран

Fullscreen javascript API или как развернуть страницу на весь экран c html5.

Давайте познакомимся с еще одним, довольно молодым API, необходимость которого уже давно терзает умы разработчиков игр, видеосайтов и прочих полноэкранных сервисов. Fullscreen javascript API пока является черновиком, но уже поддерживается в chrome, safari, ff и опере.

Internet-explorer (включая Ie10) как всегда замедляет прогресс, ну и пусть себе умирает.

Без лишних слов перейдем к примеру:

Демо

Как устроен fullscreen API?

Спецификация представляет из себя:

  • 2 метода: requestFullScreen и cancelFullScreen
  • 2 свойства обекта document: fullscreenElement и fullscreenEnabled
  • 1 событие fullscreenchange

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

Запустить отображение в полноэкранном режиме

Javascript

document.documentElement.requestFullScreen(); // отобразить страницу в полноэкранном режиме document.getElementById("video1").requestFullScreen(); // отобразить элемент в полноэкранном режиме 

Выйти из полноэкранного режима

JavaScript

2 свойства объекта document

JavaScript

fullscreenElement = document.fullscreenElement; // элемент который в данный момент находится в полноэкранним режиме fullscreenEnabled = document.fullscreenEnabled; // статус (true или false) 

Событие об изменениии режима

JavaScript

element.addEventListener("fullscreenchange", function(e)< console.log('статус fullscreen = ', document.fullscreenEnabled); >); 

Ну а пока API довольно новое, все свойства, события и методы можно использовать только с префиксами (03.2013)

Вот несколько функций, которые могут помочь.

JavaScript

//Запустить отображение в полноэкранном режиме function launchFullScreen(element) < if(element.requestFullScreen) < element.requestFullScreen(); >else if(element.mozRequestFullScreen) < element.mozRequestFullScreen(); >else if(element.webkitRequestFullScreen) < element.webkitRequestFullScreen(); >> // Выход из полноэкранного режима function cancelFullscreen() < if(document.cancelFullScreen) < document.cancelFullScreen(); >else if(document.mozCancelFullScreen) < document.mozCancelFullScreen(); >else if(document.webkitCancelFullScreen) < document.webkitCancelFullScreen(); >> var onfullscreenchange = function(e) < var fullscreenElement = document.fullscreenElement || document.mozFullscreenElement || document.webkitFullscreenElement; var fullscreenEnabled = document.fullscreenEnabled || document.mozFullscreenEnabled || document.webkitFullscreenEnabled; console.log( 'fullscreenEnabled = ' + fullscreenEnabled, ', fullscreenElement = ', fullscreenElement, ', e = ', e); >// Событие об изменениии режима el.addEventListener("webkitfullscreenchange", onfullscreenchange); el.addEventListener("mozfullscreenchange", onfullscreenchange); el.addEventListener("fullscreenchange", onfullscreenchange); 

CSS для fullscreen API

Псевдокласс :full-screen предназначен для стилизации элементов в полноэкранном режиме.

Ниже приведен пример с префиксами -webkit- и -moz- , которые через некоторое время можно будет опустить и использовать просто :full-screen

CSS

/* красный фон для полноэкранного режима */ :-webkit-full-screen < background: red; >:-moz-full-screen < background: red; >/* полноэкранное отображение */ :-webkit-full-screen video < width: 100%; height: 100%; >:-moz-full-screen video

Как открыть IFRAME в fullscreen?

Часто бывает, что контент, который вы хотите отобразить в полноэкранном режиме, находится во фрейме.

Это типичный случай встраивания видео с различных видеохостингов к себе на сайт. Для того, чтобы все работало как надо, необходимо добавить аттрибут allowfullscreen к элементу iframe . Как и все вышесказанное, он пока нуждается в префиксах.

html

 

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

Код примера в начале статьи

HTML

 

JavaScript

document.cancelFullScreen = document.cancelFullScreen || document.webkitCancelFullScreen || document.mozCancelFullScreen; function onFullScreenEnter() < console.log("Enter fullscreen initiated from iframe"); >; function onFullScreenExit() < console.log("Exit fullscreen initiated from iframe"); >; // Note: FF nightly needs about:config full-screen-api.enabled set to true. function enterFullscreen(id) < onFullScreenEnter(id); var el = document.getElementById(id); var onfullscreenchange = function(e)< var fullscreenElement = document.fullscreenElement || document.mozFullscreenElement || document.webkitFullscreenElement; var fullscreenEnabled = document.fullscreenEnabled || document.mozFullscreenEnabled || document.webkitFullscreenEnabled; console.log( 'fullscreenEnabled = ' + fullscreenEnabled, ', fullscreenElement = ', fullscreenElement, ', e = ', e); >el.addEventListener("webkitfullscreenchange", onfullscreenchange); el.addEventListener("mozfullscreenchange", onfullscreenchange); el.addEventListener("fullscreenchange", onfullscreenchange); if (el.webkitRequestFullScreen) < el.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); >else < el.mozRequestFullScreen(); >document.querySelector('#'+id + ' button').onclick = function() < exitFullscreen(id); >> function exitFullscreen(id) < onFullScreenExit(id); document.cancelFullScreen(); document.querySelector('#'+id + ' button').onclick = function()< enterFullscreen(id); >> 

CSS

:-webkit-full-screen < background: black; >:-moz-full-screen < background: black; >:-webkit-full-screen#fs_section_video.fs_section, :-webkit-full-screen#fs_section_img.fs_section < width:100%; left:0; top:0; >:-moz-full-screen#fs_section_video.fs_section, :-moz-full-screen#fs_section_img.fs_section < width:100%; left:0; >:-webkit-full-screen#fs_section_img.fs_section #i1 < display:none; >:-moz-full-screen#fs_section_img.fs_section #i1 < display:none; >:-webkit-full-screen#fs_section_img.fs_section #i2 < display:block; z-index:1; >:-moz-full-screen#fs_section_img.fs_section #i2 < display:block; z-index:1; >:-webkit-full-screen#fs_section_img.fs_section #i3 < opacity:1; display:block; z-index:2; -webkit-transition: all 2s 2s ease-in-out; >:-moz-full-screen#fs_section_img.fs_section #i3

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

Читайте также:  Get json element javascript

Жду вопросов и отзывов в комментариях 😉

Источник

Развертывание на весь экран блока

Приветствую. На сайте https://webgradients.com/ если кликнуть по любому из градиентов — он развернется на весь экран с анимацией. Как сделать подобный эффект для блока? Заметил, что при клике в body добавляется класс state-fixed к уже существующему state-show, но разобраться с js-кодом, когда он еще и сжат, мне сложно. Помогите пожалуйста.

Класс тут задается просто что бы скролл убрать. Делаете невидимый блок, при клике на градиент ставите его в то место куда кликнули, задаете нужный градиент (узнав его у элемента по которому кликнули), увеличиваете до размеров экрана . Вроде тут и в js особо лезть не надо, что бы это понять. Что уже пробовали? Какие проблемы возникли?

1 ответ 1

var ripple = $('.ripple'), // "капля" rippleSize = screenProp(), // размер капли posLeft = 0, posTop = 0; ripple.outerWidth(rippleSize * 2).outerHeight(rippleSize * 2); // задаем капле размер в 2 раза больше размера экрана, чтобы "покрыть" всю видимую область страницы $('.gradient').click(function(e) < // клик на градиент $('body').addClass('fixed'); // блокируем прокрутку экрана posLeft = e.pageX - rippleSize - $(window).scrollLeft(); // положение капли слева posTop = e.pageY - rippleSize - $(window).scrollTop(); // положение капли сверху var gradient = $(this).attr('data-gradient-css'); // получаем код градиента ripple.addClass('ripple--active').css(< // добавляем класс для увеличения и прописываем стили 'left': posLeft + 'px', 'top': posTop + 'px', 'background-image': gradient >); setTimeout(function() < // после увеличения ripple.addClass('ripple--complete'); // добавляем класс, который выровнит каплю точно по краям экрана >, 500); // время анимации увеличения >); ripple.on('click', function() < // при клике на каплю if (ripple.hasClass('ripple--complete')) < // если анимация закончилась $('body').removeClass('fixed'); // возвращаем странице прокрутку ripple.removeClass('ripple--complete ripple--active'); // удаляем классы >>); $(window).on('resize', function() < // при ресайзе окна rippleSize = screenProp(); // пересчитываем размер капли ripple.outerWidth(rippleSize * 2).outerHeight(rippleSize * 2); // и задаем ей полученные значения >); // функция для определения максимального значения из высоты и ширины экрана function screenProp() < if ($(window).width() >$(window).height()) < return $(window).width(); >else < return $(window).height(); >>
html, body < padding: 0; margin: 0; >body < overflow-x: hidden; overflow-y: auto; >body.fixed < overflow: hidden; >* < box-sizing: border-box; >.container < display: flex; flex-wrap: wrap; >.block < width: 31%; margin: 0 1%; background: #fff; border-radius: 10px; padding: 20px; >.gradient < width: 100%; height: 0; padding-bottom: 100%; border-radius: 100%; background: #000; cursor: url(https://i.imgur.com/wz8iY4B.png) 16 16, pointer; >.ripple < width: 200%; height: 200%; position: fixed; z-index: 9999; transition: transform .5s linear; transform: scale(0); transform-origin: center; border-radius: 100%; cursor: url(https://i.imgur.com/NRHTafk.png) 16 16, crosshair; >.ripple--active < transform: scale(1); >.ripple--complete

Источник

Make div ‘fullscreen’ onClick of a button?

I have a div that I want to go full-screen (100% width/height of Window size) onClick of a seperate button, image or link. How would I go about this using Javascript/jQuery?

7 Answers 7

Other solutions describe hiding browser chrome with the HTML5 fullscreen API, well supported as of Oct’20.

This jQuery will expand an element to the viewport :

You can use the Following function to make any div Full Screen

 function goFullScreen() < var elem = document.getElementById(temp); if(elem.requestFullscreen)< elem.requestFullscreen(); >else if(elem.mozRequestFullScreen) < elem.mozRequestFullScreen(); >else if(elem.webkitRequestFullscreen) < elem.webkitRequestFullscreen(); >else if(elem.msRequestFullscreen) < elem.msRequestFullscreen(); >> 

And to exit the Full Screen you can use the following function

 function exitFullScreen() < if(document.exitFullscreen)< document.exitFullscreen(); >else if(document.mozCancelFullScreen) < document.mozCancelFullScreen(); >else if(document.webkitExitFullscreen) < document.webkitExitFullscreen(); >else if(document.msExitFullscreen) < document.msExitFullscreen(); >> 

The code works on any browser.

#HTML #JS $( '#button' ).click( function() < $( '#some_id' ).width( $( window ).width() ); $( '#some_id' ).height( $( window ).height() ); >); 

you can use this functions to get the width and height

$(window).width(); $(window).height(); $(document).width(); $(document).height(); 
var w = $(document).width(); var h = $(document).height(); $("#theid").css('width',w); $("#theid").css('height',h); 

Here’s a tweaked version of my answer from yesterday:

$(':button').click(function() < $('div >div').css(< position:'absolute', //or fixed depending on needs top: $(window).scrollTop(), // top pos based on scoll pos left: 0, height: '100%', width: '100%' >); >); 

You’ll want a fixed position element at 100% width and height , if you don’t have a background color or image you’ll be able to click through it. Set z-index higher then all other elements to ensure it is at the front if you need that.

Читайте также:  Using classpath with java

You can use the Following function to make any div Full Screen

 function goFullScreen() < var elem = document.getElementById(temp); if(elem.requestFullscreen)< elem.requestFullscreen(); >else if(elem.mozRequestFullScreen) < elem.mozRequestFullScreen(); >else if(elem.webkitRequestFullscreen) < elem.webkitRequestFullscreen(); >else if(elem.msRequestFullscreen) < elem.msRequestFullscreen(); >> 

And to exit the Full Screen you can use the following function

 function exitFullScreen() < if(window.exitFullscreen)< window.exitFullscreen(); >else if(window.mozCancelFullScreen) < window.mozCancelFullScreen(); >else if(window.webkitExitFullscreen) < window.webkitExitFullscreen(); >else if(window.msExitFullscreen) < window.msExitFullscreen(); >> 

The code works on any browser.

in exitFullscreen() <> document is not active and output an error, change it to window

Источник

Scale a div to fit in window but preserve aspect ratio

How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?

Not a single one of the answers to this question achieve the desired result. Preserving the aspect ratio is trivial but getting it to be the correct aspect ratio AND always fitted to or smaller than the viewable area in both directions is more tricky.

6 Answers 6

You don’t need javascript for this. You can use pure CSS.

A padding-top percentage is interpreted relative to the containing block width. Combine it with position: absolute on a child element, and you can put pretty much anything in a box that retains its aspect ratio.

.aspectwrapper < display: inline-block; /* shrink to fit */ width: 100%; /* whatever width you like */ position: relative; /* so .content can use position: absolute */ >.aspectwrapper::after < padding-top: 56.25%; /* percentage of containing block _width_ */ display: block; content: ''; >.content < position: absolute; top: 0; bottom: 0; right: 0; left: 0; /* follow the parent's edges */ outline: thin dashed green; /* just so you can see the box */ >

The display: inline-block leaves a little extra space below the bottom edge of the .aspectwrapper box, so another element below it won’t run flush against it. Using display: block will get rid of it.

Another approach relies on the fact that browsers respect an image’s aspect ratio when you resize only its width or height. (I’ll let google generate a 16×9 transparent image for demonstration purposes, but in practice you would use your own static image.)

 
.aspectwrapper < width: 100%; position: relative; >.aspectspacer < width: 100%; /* let the enlarged image height push .aspectwrapper's bottom edge */ >.content

can you put up a jsFiddle example with a perfect box (all sides euqal) resizing using the first method? I didn’t quite get how it can be done using your first method.

Читайте также:  Html block copy text

Here you are: jsfiddle.net/ks2jH/1 Note that the key to making it a perfect box is the padding-top: 100% which means the height should be 100% of the size of the .aspectwrapper width. Since that width is set to 50%, it will resize with its parent. I also added overflow: hidden so the text wouldn’t deform the box at small sizes.

If you wanted a rectangle half as tall as it is wide, you would use padding-top: 50% . In my example above, I made a 16:9 rectangle, suitable for wide screen video, using padding-top: 56.25% (9/16 = 56.25%).

this only seems to resize against the width. so it doesn’t resize the width of the div so that the height fits. so it is not really fit-into-viewport but just rather boring old easy to achieve aspect ratio maintain.

Thanks to Geoff for the tip on how to structure the math and logic. Here’s my jQuery implementation, which I’m using to size a lightbox so it fills the window:

var height = originalHeight; var width = originalWidth; aspect = width / height; if($(window).height() < $(window).width()) < var resizedHeight = $(window).height(); var resizedWidth = resizedHeight * aspect; >else < // screen width is smaller than height (mobile, etc) var resizedWidth = $(window).width(); var resizedHeight = resizedWidth / aspect; >

This is working well for me right now across laptop and mobile screen sizes.

with little refinery this works, but your IF doesnt check for the right thing var vw=$(«#absoluteSized»).width(); var vh=$(«#absoluteSized»).height(); var divAspect=vw/vh; if(divAspect > aspect) < resizedHeight = vh; resizedWidth = resizedHeight * aspect; >else < // screen width is smaller than height (mobile, etc) resizedWidth = vw; resizedHeight = resizedWidth / aspect; >

I have a different pure HTML/CSS approach which does not rely on padding or absolute positioning. Instead it uses em units and relies on the CSS min() function plus a little bit of math.

Imagine that we want a viewport div with 16:9 aspect ratio which always fits the browser window and is centered in the axis with excess space. Here’s how we can accomplish that:

   
This should be a 16:9 viewport that fits the window.

body < width: 100vw; height: 100vh; margin: 0; display: flex; justify-content: center; align-items: center; background-color: white; font-size: min(1vw, 1.778vh); >div.viewport < width: 100em; height: 56.25em; background-color: lightblue; >div.viewport > p

You can experiment with this in a sample JSFiddle here.

The secret sauce is in the body font-size . It should be set to min(1vw, Avh) , where A is the aspect ratio you want the div to have, i.e. width / height . In the example above we’re using 1.778, which is approximately 16 / 9.

In CSS, em units are based on the font-size of the element, which is inherited from parent element if not explicitly set. For your viewport div, set the width to 100em (NOT rem) and the height to Iem , where I is the inverse of the aspect ratio expressed as a percentage, i.e. 100 / A or 100 * height / width . In the example above we’re using 56.25, which is 100 * 9 / 16.

One bonus of this approach is that all of your nested elements may also use em units so that they always scale precisely with the size of the viewport. You can see this used on the p element in the example.

Note that as an alternative to the above, you may set the font-size on your html element and use rem units everywhere. CSS rem units are similar to em units but always relative to the root element’s font-size .

Источник

Оцените статью