Move to window javascript

Move to window javascript

JavaScript allows you to move a window either relatively (by the amount specified), or absolutely (to the coordinates on the screen specified). For your convenience, here are the related window methods again:

Methods Description
moveBy(dx, dy) Moves a window by the specified amount in pixels
moveTo(x,y) Moves a window to the specified pixel values

— moveBy() method

Use moveBy() to move a window either horizontally, vertically, or both, by the specified amount in pixels. Note that a negative parameter value causes the window to be moved in the opposite direction. Here are a couple of examples: Example #1: Move to the Left!

  • The moveBy() function is used to move the window down 10 pixels, then right, then up, and finally, left, back to the window’s original position on the screen. Note where and how «x» appears in each of the four moveBy() functions.
  • A «for» loop is implemented around these moveBy() functions to execute the shaking action 20 times.
  • An «earthquake» on the window is produced!

-moveTo() method

moveTo(), as the method name implies, moves a window to the specified coordinates on the screen. Two common uses of it is to move a newly opened window to the upper left corner of the screen, and to the dead center. Let’s see an example of each!

Example #3: Move to upper-left corner

Example #4: Move to center

The center coordinates of the screen in the second example is calculated by determining the screen’s dimensions, dividing that by 2, and subtracting half of either the window’s width/height from it. In other words, in order to center a window, it’s dimensions have to be known before hand.

Читайте также:  Python deep copy object

Источник

Window: moveTo() method

The moveTo() method of the Window interface moves the current window to the specified coordinates.

Note: This function moves the window to an absolute location. In contrast, window.moveBy() moves the window relative to its current location.

Syntax

Parameters

  • x is the horizontal coordinate to be moved to.
  • y is the vertical coordinate to be moved to.

Return value

Examples

This example moves the window to the top-left corner of the screen.

function origin()  window.moveTo(0, 0); > 

Specifications

Browser compatibility

BCD tables only load in the browser

As of Firefox 7, websites can no longer move a browser window in the following cases:

  1. You can’t move a window or tab that wasn’t created by Window.open() .
  2. You can’t move a window or tab when it’s in a window with more than one tab.

See also

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Window: moveBy() method

The moveBy() method of the Window interface moves the current window by a specified amount.

Note: This function moves the window relative to its current location. In contrast, window.moveTo() moves the window to an absolute location.

Syntax

Parameters

  • deltaX is the amount of pixels to move the window horizontally. Positive values are to the right, while negative values are to the left.
  • deltaY is the amount of pixels to move the window vertically. Positive values are down, while negative values are up.

Return value

Examples

This example moves the window 10 pixels to the right and 10 pixels up.

function budge()  moveBy(10, -10); > 

Specifications

Browser compatibility

BCD tables only load in the browser

As of Firefox 7, websites can no longer move a browser window in the following cases:

  1. You can’t move a window or tab that wasn’t created by Window.open() .
  2. You can’t move a window or tab when it’s in a window with more than one tab.

See also

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Перемещение окна и прокрутка страницы в JavaScript

В этой теме познакомимся с методами глобального объекта window, предназначенными для перемещения окна (moveTo и moveBy), изменения его размера (resizeTo, resizeBy) и выполнения прокрутки страницы (scrollTo и scrollBy).

Перемещение окна

В JavaScript имеются следующие методы объекта window для перемещения окна:

  • moveTo – абсолютное перемещение окна в указанные координаты экрана;
  • moveBy – перемещения окна на указанное количество пикселей относительно его текущего положения.

Синтаксис метода « window.moveTo »:

window.moveTo(x, y); // x и у – это координаты точки (соответственно горизонтальная и вертикальная), в которую необходимо переместить левый верхний угол окна браузера

Пример, в котором переместим окно в точку (50, 75):

Метод moveTo() объекта window

Пример, в котором произведём перемещение окна в левый верхний угол экрана:

Синтаксис метода « window.moveBy »:

window.moveBy(deltaX, deltaY); // deltaX и deltaY – количество пикселей, на которое следует переместить окно соответственно по горизонтали и вертикали относительно его текущего положения

Например, сдвинем окно на 75px вправо и на 100px вниз:

Метод moveBy() объекта window

В большинстве браузеров перемещение окна доступно только при выполнении следующих условий:

  • окно (или вкладка) должно быть создано с помощью window.open ;
  • в окне не должно находиться более чем одной вкладки.
  .       

Изменение размеров окна

Методы объекта window для изменения размеров окна:

  • resizeTo – изменяет ширину ( outerWidth ) и высоту ( outerHeight ) окна на указанные значения;
  • resizeBy – изменяет ширину ( outerWidth ) и высоту ( outerHeight ) окна на указанные величины относительно его текущих размеров.

В JavaScript методы resizeTo и resizeBy выполняют эти действия только посредством изменения положения правого нижнего угла (координаты верхнего левого угла при этом остаются неизменными).

// width и height – новая ширина и высота окна в пикселях window.resizeTo(width, height);

Например, изменим ширину и высоту окна так, чтобы он занимал ¼ доступного экрана:

// получаем 1/2 доступной ширины экрана в пикселях const width = window.screen.availWidth / 2; // получаем 1/2 доступной высоты экрана в пикселях const height = window.screen.availHeight / 2; // устанавливаем окну ширину и высоту window.resizeTo(width, height);
window.resizeBy(deltaX, deltaY); // deltaX и deltaY – количество пикселей на которые нужно увеличить размеры окна соответственно по горизонтали и вертикали

Например, уменьшим размеры окна (его ширину и высоту) на 50px:

  .       

Прокрутка документа

В JavaScript имеются следующие методы объекта window для прокрутки документа:

  • scroll ( scrollTo ) — прокручивает страницу до указанного места в абсолютном выражении;
  • scrollBy — прокручивает документ на определённое количество пикселей относительно текущей позиции.

Синтаксис метода scroll (метод scrollTo выполняет то же самое, что scroll и не отличается по синтаксису):

// 1 вариант window.scroll(left, top); // left - по оси Х, top - по оси Y // 2 вариант window.scroll({ left: 0, // до какого количества пикселей прокрутить вправо top: 0, // до какого количество пикселей прокрутить вниз behavior: 'auto'; // определяет плавность прокрутки: 'auto' - мгновенно (по умолчанию), 'smooth' - плавно });

Синтаксис метода scrollBy :

// 1 вариант window.scrollBy(left, top); // left - по оси Х, top - по оси Y // 2 вариант window.scrollBy({ left: 0, // на какое количество пикселей прокрутить вправо от текущей позиции top: 0, // на какое количество пикселей прокрутить вниз от текущей позиции behavior: 'auto'; // определяет плавность прокрутки: 'auto' - мгновенно (по умолчанию), 'smooth' - плавно });

Пример, в котором создадим 3 ссылки, при нажатии на которые будем вызывать метод scroll или scrollBy с определёнными значениями:

JavaScript Window API - Свойства scroll, scrollTo и scrollBy

вниз мгновенно (до 2000) вниз плавно (на +200) вверх плавно (до 0)  

Источник

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