onClick javascript: навигация с изменением фоновых изображений css / двух типов - PullRequest
1 голос
/ 18 марта 2012

Я делаю сайт с 2 навигациями (переходами), включая ссылки, каждая из которых находится в другом разделе.

Когда ссылка нажата, она должна изменить свое фоновое изображение в css (изменить класс). И только одна ссылка этого класса может изменить фон.

Во второй навигации есть одна ссылка, которая также включена в навигацию 1. Также во втором меню есть два разных фоновых изображения для «переключения».

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

Сайт: http://enlifer.de/test25/zp-kazachkova.html

Вторая навигация находится на высоте логотипа. Если щелкнуть «Leistungen» во второй навигационной панели, первая также должна изменить фон по умолчанию и наоборот.

Следующий код актуален.

Первая навигация

<navigation>
    <ul id="nav">

        <li class="link" onclick="mark(this)">  <a href="#" class="textlink">Kontakt</a>    </li>
        <li class="link" onclick="mark(this)">  <a href="#" class="textlink">Anfahrt</a>    </li>
        <li class="link" onclick="mark(this)">  <a href="#" class="textlink">Leistungen</a> </li>
        <li class="link" onclick="mark(this)">  <a href="#" class="textlink">Praxisteam</a> </li>

    </ul>

</navigation>

Вторая навигация

<up>
    <ul id="up">

        <li class="uplink-l" onclick="l_mark(this)">    <a href="#" class="uptextlink-l">Leistungen</a> </li>
        <li class="uplink-i" onclick="i_mark(this)">    <a href="#" class="uptextlink-i">Impressum</a>  </li>

    </ul>

</up>

JavaScript

<script type="text/javascript">
function mark(cell)
{
for(i=0; i <
document.getElementById("nav").getElementsByTagName("li").length; i++)
{
document.getElementById("nav").getElementsByTagName("li")[i].className="link";
}
cell.className="linkactive";
}

function l_mark(cell)
{
for(i=0; i <
document.getElementById("up").getElementsByTagName("li")[0].length; i++)
{
document.getElementById("up").getElementsByTagName("li")[0][i].className="uplink-l";
}
cell.className="uplink-l-active";
}

function i_mark(cell)
{
for(i=0; i <
document.getElementById("up").getElementsByTagName("li")[1].length; i++)
{
document.getElementById("up").getElementsByTagName("li")[1][i].className="uplink-i";
}
cell.className="uplink-i-active";
}

window.onload = setActive;
</script>

Спасибо!

1 Ответ

0 голосов
/ 19 марта 2012

«Leistungen» имеет класс lmark, а «Impressum» - imark. Ваша функция Javascript для элементов, классифицированных как lmark, сбрасывает фон для всех других элементов, классифицированных как lmark, но не для элементов, классифицированных по imark. То же самое для функции, касающейся imark.

Если вам нужен только один фон не по умолчанию для всех элементов lmark и imark, правильный (вероятно, правильный, хотя и не проверенный) код:

function li_mark(cell) {
    var elts=document.getElementById("up").getElementsByTagName("li"); //store the elements we need in a local variable so we don't have to rewrite all that line (and the browser won't have to do the fetching job again), we don't care if they're L-type or I-type
    for(var i in elts)
        if(elts[i].className && elts[i].className.length>=8) //check if there is a className and it is at least as long as "uplink-X", otherwise we don't process the element and skip to the next
            elts[i].className="uplink-"+elts[i].className.charAt(7); //we retrieve the letter for the type of class (L or I), and we append it to "upload-" to redefine the class of the current element
    cell.className+="-active"; //after the loop, all elements have their default class, so we just need to append "-active" to the one we want to be active
}

Затем все ваши звонки на l_mark(this) и i_mark(this) должны быть просто заменены звонками на li_mark(this).

P.S .: не связано, но мой текущий браузер (Firefox), похоже, не похож на window.onload=setActive;, говоря, что "setActive не определено" ...

Редактировать в соответствии с комментариями , просмотрев ваш файл JS (scripttests.js):

Вам по-прежнему нужны 2 функции, mark() и li_mark(), потому что для mark() ваш активный класс имеет форму <className>active вместо <className>-X-active (не тот же шаблон в именовании классов, и нет необходимости чтобы восстановить характер Lor I).

Другая часть проблемы заключается в том, что вы вызываете cell.className+="-active" дважды в одной и той же ячейке в одной имеющейся у вас функции.

Последняя часть проблемы заключается в том, что вы забыли инструкцию в if второго цикла: поскольку нет квадратных скобок, инструкция, которая выполняется, когда это if истинно, равна cell.className+="-active" .. . выполняется столько раз, сколько выполняется цикл, и значение if равно true.

(вероятно) рабочая версия будет:

function li_mark(cell) {
    var elts=document.getElementById("up").getElementsByTagName("li"); //store the elements we need in a local variable so we don't have to rewrite all that line (and the browser won't have to do the fetching job again), we don't care if they're L-type or I-type
    for(var i in elts)
        if(elts[i].className && elts[i].className.length>=8) //check if there is a className and it is at least as long as "uplink-X", otherwise we don't process the element and skip to the next
            elts[i].className="uplink-"+elts[i].className.charAt(7); //we retrieve the letter for the type of class (L or I), and we append it to "upload-" to redefine the class of the current element
    if(cell && cell.className && cell.className.length>=8) { //if we passed an argument, then it must be a cell to activate, with a basic check on its className
        cell.className+="-active"; //after the loop, all elements have their default class, so we just need to append "-active" to the one we want to be active
        mark(); //we call mark() with no argument to reset all the items managed by mark(), we call it in this if-block to avoid infinite recursion
    }
}
function mark(cell) {
    var elts=document.getElementById("nav").getElementsByTagName("li"); //store the elements we need in a local variable so we don't have to rewrite all that line (and the browser won't have to do the fetching job again), we don't care if they're L-type or I-type
    for(var i in elts)
        if(elts[i].className) //check if there is a className, otherwise we don't process the element and skip to the next
            elts[i].className="link"; //we set back to the default class
    if(cell && cell.className) { //if we passed an argument, then it must be a cell to activate
        cell.className+="active"; //after the loop, all elements have their default class, so we just need to append "active" to the one we want to be active
        li_mark(); //we call li_mark() with no argument to reset all the items managed by li_mark(), we call it in this if-block to avoid infinite recursion
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...