Javascript getelementbyid style left

Передать параметр в getElementById

Доброго времени суток!
Есть меню на CSS и функция, при срабатывании которой div с контентом «выезжает» с левой стороны экрана.
Дивов много, и писать отдельно одинаковые функции для каждого из них нерационально.
Поэтому ищу обходные пути. Возникла идея передать id дива как параметр функции в onclick, чтобы функция была одна, а onclick для каждого раздела меню свой, но ничего не выходит.
JS только начал изучать, поэтому ищу способ попроще.
Заранее благодарю за помощь.

li>a href="#2" onclick="slider('block')">Раздел_1a>li> function slider(q) { if (parseInt(document.getElementById(q).style.left)  205) { document.getElementById(q).style.left = parseInt(document.getElementById(q).style.left)+10 setTimeout("slider()",8) } }

Не получается через type=»hidden» и getElementById передать значение
Здравствуйте. У меня есть скрипт: <script type="text/javascript"> function confirmDelete()

Передать параметр
Здравствуйте. Такая проблема: Мне нужно в select.php передать значение prefix. Дописал по.

Передать параметр из js в php
Всем привет! Нужна помощь. Аяксом передаю параметр, а в php его не могу вывести. function send(a).

Эксперт по математике/физике

Onclick позволяет узнать внутри себя, кто вызвал это событие, в частности, id кнопки или ссылки, которая была нажита. id выдвигаемого функцией slider блока однозначно определяется по id нажатой кнопки. Как — не знаю, потому что это зависит от того, как Вы раздаёте id Вашим DOM-объктам.
Допустим, Вы имеете функцию

function IdCorresp(buttonId) { var divId = . return divId; }

тогда Вы можете всем-всем кнопкам приписать ClickEvent из следующего кода (кстати, посмотрите на функцию slider, у Вас id в setTimeout не передаётся, у меня — замыкается)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
function ClickEvent() { var buttonId = . // например, this.id; var divId = IdCorresp(buttonId); function slide() { var el = document.getElementById(divId); if (parseInt(el.style.left)  205) { el.style.left = parseInt(el.style.left)+10; setTimeout(slide, 8); } } slide(); // запускаем }

Спасибо за помощь!
Логику, кажется, понял, но на практике ничего подобного не встречал.
Если вас не затруднит, можете подправить мой код ?
Чтобы при нажатии на «Раздел_1» выезжал первый блок (block), а при нажатии «Раздел_2» (block1).
Заранее благодарю! А то голова совсем не варит)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
li>a href="#2" id="" onclick="">Раздел_1a>li> li>a href="#3" id="" onclick="">Раздел_2a>li> script> function IdCorresp(buttonId) { var divId = . return divId; } function ClickEvent() { var buttonId = . // например, this.id; var divId = IdCorresp(buttonId); function slide() { var el = document.getElementById(divId); if (parseInt(el.style.left)  205) { el.style.left = parseInt(el.style.left)+10; setTimeout(slide, 8); } } slide(); // запускаем } script> div id="block" class="bord" style="position:absolute; left:-1010px; top:70px;WIDTH: 880px; HEIGHT: 540px; padding: 20px; overflow:auto;">Контентdiv> div id="block1" class="bord" style="position:absolute; left:-750px; top:100px;WIDTH: 700px; HEIGHT: 500px; padding: 20px; overflow:auto;">Контентdiv>

Эксперт по математике/физике

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
html> head> head> body> ul> li>a href="#2" id="button1" onclick="ClickEvent.call(this);">Раздел_1a>li> li>a href="#3" id="button2" onclick="ClickEvent.call(this);">Раздел_2a>li> ul> script> function IdCorresp(buttonId) { if(buttonId == "button1") return "block"; if(buttonId == "button2") return "block1"; } function ClickEvent() { var buttonId = this.id; var divId = IdCorresp(buttonId); if(! divId) return; function slide() { var el = document.getElementById(divId); if (parseInt(el.style.left)  205) { el.style.left = parseInt(el.style.left)+10; setTimeout(slide, 8); } } slide(); } script> div id="block" class="bord" style="position:absolute; left:-1010px; top:70px;WIDTH: 880px; HEIGHT: 540px; padding: 20px; overflow:auto;">Контент 1div> div id="block1" class="bord" style="position:absolute; left:-750px; top:100px;WIDTH: 700px; HEIGHT: 500px; padding: 20px; overflow:auto;">Контент 2div> body> html>
document.getElementById("button1").onclick = ClickEvent;

Эксперт JSЭксперт HTML/CSS

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

Помогите пожалуйста.
Нужно, чтобы при нажатии на другую ссылку, тот блок, который уже находится в видимой части экрана, задвигался, а после выдвигался тот, который был вызван т.е. чтобы они заменяли друг друга.
Никак не пойму как это можно реализовать. Заранее благодарю!

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
function IdCorresp(buttonId) { if(buttonId == "button1") return "block1"; if(buttonId == "button2") return "block2" ; if(buttonId == "button3") return "block3" ; if(buttonId == "button4") return "block4" ; if(buttonId == "button5") return "block5" ; if(buttonId == "button6") return "block6" ; } function IdCorresp_(buttonId) { if(buttonId == "button7") return "block1"; if(buttonId == "button8") return "block2" ; if(buttonId == "button9") return "block3" ; if(buttonId == "button10") return "block4" ; if(buttonId == "button11") return "block5" ; if(buttonId == "button12") return "block6" ; } function ClickEvent() { var buttonId = this.id; var divId = IdCorresp(buttonId); if(! divId) return; function slide() { var el = document.getElementById(divId); if (parseInt(el.style.left)  0) { el.style.left = (parseInt(el.style.left)+10)+"px"; setTimeout(slide, 8); } } slide(); } function ClickBack() { var buttonId = this.id; var divId = IdCorresp_(buttonId); if(! divId) return; function slideback() { var el = document.getElementById(divId); if (parseInt(el.style.left) > -1100) { el.style.left = (parseInt(el.style.left)-10)+"px"; setTimeout(slideback, 8); } } slideback(); }
li>a href="#1" id="button1" onclick="ClickEvent.call(this);">Пункт 1/a>/li> li>a href="#2" id="button2" onclick="ClickEvent.call(this);">Пункт 2/a>/li> li>a href="#3" id="button3" onclick="ClickEvent.call(this);">Пункт 3/a>/li> div id="block1" class="bord" style="left:-1100px; top:-50px;">/div> div id="block2" class="bord" style="position:absolute; left:-1500px; top:-50px;">/div>

Добавлено через 2 часа 6 минут
Есть такая идея:
Две переменные.
При клике на ссылку (кнопку) id div’a записывается в одну переменную, а в другой записан id невидимого div’a, видимый выдвигается в центр экрана, а невидимый, к примеру, на 1500 пикселей в левую сторону. После этого во вторую переменную записывается id видимого в данный момент блока, а при нажатии на другую кнопку, в первую переменную записывается id нужного в данный момент div’a. Таким образом id будут постоянно меняться и видим будет только необходимый в данный момент. Только не знаю, возможно ли реализовать данный способ.
Может есть варианты лучше ?

Не получается передать параметр в функцию
Подскажите, пожалуйста, хочу сделать так чтобы при наджатии кнопки фон страницы изменялся, но не.

JS: Передать параметр в командную строку
На предприятии есть программа для управления компьютерами — лаунчер, в него попросили добавить.

Источник

Style left Property

The left property sets or returns the left position of a positioned element.

This property specifies the left position of the element including padding, scrollbar, border and margin.

Tip: A positioned element is an element with the position property set to: relative, absolute, or fixed.

Tip: To set or return the right position of a positioned element, use the right property.

Browser Support

Syntax

Property Values

Value Description
auto Lets the browser set the left position. This is default
length Defines the left position in length units. Negative values are allowed
% Sets the left position in % of the width of the parent element
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: auto
Return Value: A String, representing the left position of a positioned element
CSS Version CSS2

More Examples

Example

Set the left position of a element:

Example

Using negative values — Set the left position of a element:

Example

Return the left position of a element:

Источник

Style left Property

The left property sets or returns the left position of a positioned element.

This property specifies the left position of the element including padding, scrollbar, border and margin.

Tip: A positioned element is an element with the position property set to: relative, absolute, or fixed.

Tip: To set or return the right position of a positioned element, use the right property.

Browser Support

The left property is supported in all major browsers.

Syntax

Property Values

Value Description
auto Lets the browser set the left position. This is default
length Defines the left position in length units. Negative values are allowed
% Sets the left position in % of the width of the parent element
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: auto
Return Value: A String, representing the left position of a positioned element
CSS Version CSS2

More Examples

Example

Set the left position of a element:

Example

Using negative values — Set the left position of a element:

Example

Return the left position of a element:

Источник

Javascript Reference — HTML DOM Style left Property

The left property sets or gets the left position of a positioned element.

Browser Support

left Yes Yes Yes Yes Yes

Syntax

object.style.left='auto|length|%|initial|inherit' 

Property Values

Value Description
auto Default value. The browser does the calculation.
length Set left in px, cm, etc. Negative values allowed
% Sets the left edge position in % of containing element. Negative values allowed
inherit Inherit the left property from the parent element

Technical Details

Example

The following code shows how to set the left position of a element.

 !DOCTYPE html> html> head> style> #myBtn !-- ww w . java 2s . co m--> position: absolute; >  body> button type="button" >"myBtn" onclick="myFunction()">test script> function myFunction() < document.getElementById("myBtn").style.left = "100px"; >   

The code above is rendered as follows:

Example 2

The following code shows how to set the left position of a element.

 !DOCTYPE html> html> head> style> #myDIV !--from www . j a v a 2 s .co m--> position: absolute; width: 100px; height: 100px; background-color: coral; color: white; >  body> button onclick="myFunction()">test div >"myDIV">myDIV script> function myFunction() < document.getElementById("myDIV").style.left = "100px"; >   

The code above is rendered as follows:

Example 3

The following code shows how to use negative values in left position of a element.

 !DOCTYPE html> html> head> style> #myDIV !--from w w w . ja va2s . c o m--> position: absolute; width: 100px; height: 100px; background-color: coral; color: white; >  body> button onclick="myFunction()">test div >"myDIV">myDIV script> function myFunction() < document.getElementById("myDIV").style.left = "-30px"; >   

The code above is rendered as follows:

Example 4

The following code shows how to get the left position of a element.

 !DOCTYPE html> html> body> !-- www . ja v a 2 s.c o m--> div >"myDiv" style="position:absolute;left:255px;">This is a div element. button type="button" onclick="myFunction()">test script> function myFunction() < console.log(document.getElementById("myDiv").style.left); >   

The code above is rendered as follows:

java2s.com | © Demo Source and Support. All rights reserved.

Источник

Читайте также:  Get year with php
Оцените статью