Javascript display none position

Javascript DOM Style display Property

The display property gets and sets the element’s display type.

The HTML elements are mostly «inline» or «block» elements:

  • An inline element has floating content on its left and right side.
  • A block element fills the entire line.

In other words, an inline element can share the same line with other elements, while the block element always starts a new line.

The display property can show or hide an element.

It is similar to the visibility property.

If you set display:none, it hides the entire element and removes it from the layout, while visibility:hidden means that the element will be invisible, but the element occupy in its original position and size.

If an element is a block element, its display type can also be changed with the float property.

Browser Compatibility

Syntax

Return the display property:

let a = object.style.display;
object.style.display = value;

Property Values

Value Element is rendered as
block a block-level element
compact

Default Value

Return Value

A String, representing the display type of an element.

More Examples

Difference between the display property and the visibility property:

function demoDisplay() < document.getElementById("myP1").style.display = "none"; > function demoVisibility() < document.getElementById("myP2").style.visibility = "hidden"; >
!DOCTYPE html> html> body> p id="myP1">This is some text. p id="myP2">This is some text. input type="button" onclick="demoDisplay()" value="Hide text with display property"> input type="button" onclick="demoVisibility()" value="Hide text with visibility property"> script> function demoDisplay() !-- w w w . d e m o 2 s . c o m--> document.getElementById("myP1").style.display = "none"; > function demoVisibility() < document.getElementById("myP2").style.visibility = "hidden"; >   

Example

Toggle between hiding and showing an element:

function myFunction() < let x = document.getElementById('myDIV'); if (x.style.display === 'none') < x.style.display = 'block'; > else < x.style.display = 'none'; > >
!DOCTYPE html> html> head> style> #myDIV !-- w w w . d e m o 2 s. c o m --> width: 500px; height: 500px; background-color: lightblue; >  body> p>Click the "Test" button to toggle between hiding and showing the DIV element: button onclick="myFunction()">Test div id="myDIV"> This is my DIV element. p>b>Note: The element will not take up any space when the display property set to "none". script> function myFunction() < let x = document.getElementById('myDIV'); if (x.style.display === 'none') < x.style.display = 'block'; > else < x.style.display = 'none'; > >   

Example

Difference between «inline», «block» and «none»:

let whichSelected = x.selectedIndex; let sel = x.options[whichSelected].text; let elem = document.getElementById("mySpan"); elem.style.display = sel;
!DOCTYPE html> html> body> p>Select a display type in the list below to change span id="mySpan" style="color:blue;">this span element's  display type. select onchange="myFunction(this);" size="3"> option>block option>inline option>none !-- w w w . d e m o 2 s . c o m --> script> function myFunction(x) < let whichSelected = x.selectedIndex; let sel = x.options[whichSelected].text; let elem = document.getElementById("mySpan"); elem.style.display = sel; >   

Example

Return the display type of a

element:

console.log(document.getElementById("myP").style.display);
!DOCTYPE html> html> body> p id="myP" style="display:none;">This is a p element. button type="button" onclick="myFunction()"> Return the display type of p  p id='demo'>  script> function myFunction() < document.getElementById('demo').innerHTML = document.getElementById("myP").style.display; >   

  • Javascript DOM Style cssFloat Property
  • Javascript DOM Style cursor Property
  • Javascript DOM Style direction Property
  • Javascript DOM Style display Property
  • Javascript DOM Style emptyCells Property
  • Javascript DOM Style filter Property
  • Javascript DOM Style flex Property

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Style display Property

The display property sets or returns the element’s display type.

Elements in HTML are mostly «inline» or «block» elements: An inline element has floating content on its left and right side. A block element fills the entire line, and nothing can be displayed on its left or right side.

The display property also allows the author to show or hide an element. It is similar to the visibility property. However, if you set display:none , it hides the entire element, while visibility:hidden means that the contents of the element will be invisible, but the element stays in its original position and size.

Tip: If an element is a block element, its display type can also be changed with the float property.

Browser Support

Syntax

Return the display property:

Property Values

Value Description
block Element is rendered as a block-level element
compact Element is rendered as a block-level or inline element. Depends on context
flex Element is rendered as a block-level flex box. New in CSS3
inline Element is rendered as an inline element. This is default
inline-block Element is rendered as a block box inside an inline box
inline-flex Element is rendered as a inline-level flex box. New in CSS3
inline-table Element is rendered as an inline table (like ), with no line break before or after the table
list-item Element is rendered as a list
marker This value sets content before or after a box to be a marker (used with :before and :after pseudo-elements. Otherwise this value is identical to «inline»)
none Element will not be displayed
run-in Element is rendered as block-level or inline element. Depends on context
table Element is rendered as a block table (like ), with a line break before and after the table)
table-caption Element is rendered as a table caption (like )
table-cell Element is rendered as a table cell (like and )
table-column Element is rendered as a column of cells (like )
table-column-group Element is rendered as a group of one or more columns (like )
table-footer-group Element is rendered as a table footer row (like )
table-header-group Element is rendered as a table header row (like )
table-row Element is rendered as a table row (like
table-row-group Element is rendered as a group of one or more rows (like )
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: inline
Return Value: A String, representing the display type of an element
CSS Version CSS1

More Examples

Example

Difference between the display property and the visibility property:

function demoDisplay() <
document.getElementById(«myP1»).style.display = «none»;
>

function demoVisibility() document.getElementById(«myP2»).style.visibility = «hidden»;
>

Example

Toggle between hiding and showing an element:

function myFunction() <
var x = document.getElementById(‘myDIV’);
if (x.style.display === ‘none’) <
x.style.display = ‘block’;
> else <
x.style.display = ‘none’;
>
>

Example

Difference between «inline», «block» and «none»:

function myFunction(x) <
var whichSelected = x.selectedIndex;
var sel = x.options[whichSelected].text;
var elem = document.getElementById(«mySpan»);
elem.style.display = sel;
>

Example

Return the display type of a

element:

Источник

Всплывающие меню, или position absolute

Всплывающие меню, или position absolute

Много материала было перекопано мною, для того, что бы понять как работают всплывающие меню.. Парой приходится возобновлять поиски, ибо иногда решение найдено мной, не соответствует моим желаниям/потребностям. Помню как копался в километровом коде, генерированный программой для создание подобных меню (название программы к сожалению не могу припомнить =() После чего решил обходится лишь тем, что узнал. Для создания простого, но все же эффективного, всплывающего меню понадобится лишь прибегнуть к 3-м элементам css стиля, и маленького скрипта на javascript.. Добро пожаловать на 2-ой, написанный мной, «корявый» урок по javascript =)))

Как уже говрил, нам понадобится 3 css элемента:

position:absolute;
display:none/block;
margin-left:Xpx;

Первый помещает объект, буть то «div» или «p», в абсолютную позицию на экране, совершенно не трогая все остальные объекты. Вы можете поместить объект в центре экрана, или с лева, или например поверх какого нить др объекта. Выражаясь «задротским» языком — читерская штука =)

Второй элемент, визуально (т.е. в коде он остается) прячет объект при свойстве none, а при свойстве block показывает на странице (и в коде тоже)

С помощью 3-его элемента мы сдвинем наш абсолютный объект влево

При наведение курсора мыши, скажем на «div», javascript переключает свойство элемента display с none на block, а при перемещение курсора мыши за границу объекта «div» свойство переключается обратно на none

Для начала напишем 2 объекта «div» и обозначим их id (это пригодится для javascrip, и для меня. удобнее объяснять =))

После поместим во 2-ой «div» следующий стиль

Теперь можно приступить к написанию javascript функции

function menu(id,oc)
//id - собственно id нашего 'а
//oc - индикатор отвечающий за открытия меню (0) и закрытия (1)
var el = document.getElementById(id);//немного упрощаем запись
if(oc == 0) el.style.display = "block";//если переменная oc равна 0
//(т.е. открыть меню) то меняем в стиле, объекта , свойство none
//на свойство block
else el.style.display = "none";//если же переменная oc равна 1
//то меняем в стиле, объекта , свойство block
//на свойство none
>

Для вызова этой функции используем 2 обработчика событий:

onMouseOver=""//если курсор на границе объекта
onMouseOut=""//если курсор за границей объекта

Вписываем их в 1-ый «div» получаем следующую запись

Заменив тег «div» на более симпатичный тег «p» и добавив пару стилей, получаем следующий, готовый к работе, код:

 
onMouseOut="menu(2,1);">

Меню 1


Подменю 1


Источник

Читайте также:  With block python ошибка
Оцените статью