2014-04-28 4 views
0

Как я могу отобразить один iframe за раз? Итак, у меня есть веб-страница индекса, которая имеет ссылки на nav в iframes, но я хочу, чтобы iframes отображался только при нажатии ссылок. Сейчас они оба отображаются. Это решение для javascript? Я новичок в кодировании, поэтому, если это так, мне может быть проще, если я не буду использовать iframes и просто настроить разные страницы и настроить идентификатор.загружать только iframe при нажатии ссылки

Вот мой код: http://jsfiddle.net/r2mmb/

HTML

<header> 
<div id="logo"> 
<img src="../../assets/images/logo.png" alt=""> 
</div> 
<nav> 
<ul> 
<li><a href="iframetoursprices.html" target="toursprices"> 
    TOURS,PRICES &amp; STANDARD FLIGHTS</a></li> 
<li><a href="#">MEET THE STAFF</a></li> 
<li><a href="iframegallery.html" target="gallery">Gallery</a></li> 
</ul> 
</nav> 
    </header> 

<div class="mainInfo"> 
<iframe src="iframetoursprices.html" name="toursprices"></iframe> 
<iframe src="iframegallery.html" name="gallery"></iframe> 
</div> 
+0

какой-либо причине вы не просто использовать _one_ IFRAME, а затем использовать ссылки с целевой атрибут для загрузки либо один, либо другой страницы в том, что ...? – CBroe

+0

Который вы действительно хотите: (A) Загружен только один или (B) Показывается только один? – Randy

+0

@CBroe привет да, который мог работать, просто никогда не думал об этом. вы могли бы продемонстрировать в скрипке, пожалуйста? – ev9604

ответ

0

Вы можете попробовать добавить класс .active в IFRAME, что вы combiene

и добавляет событие OnClick в меню.

посмотрите на этот пример.

http://jsfiddle.net/r2mmb/1/

1

Один подход, который я хотел бы предложить сначала скрывая все элементы с помощью CSS:

iframe { 
    display: none; 
} 

И создать правило CSS, используя class, чтобы показать, что элемент:

iframe.inUse { 
    display: block; 
} 

С jQuery:

// binds a click handler to all 'a' elements with a 'target' attribute: 
$('a[target]').click(function(){ 
    // creates a reference to the clicked-link: 
    var clickedEl = this; 

    // gets all 'iframe' elements in the document: 
    $('iframe') 
     // removes the 'inUse' class from all of them: 
     .removeClass('inUse') 
     // filters the collection of 'iframe' elements: 
     .filter(function(){ 
      // we keep only the 'iframe' whose 'name' attribute 
      // is equal to the 'name' attribute of the clicked 'a': 
      return this.name === clickedEl.target; 
     // and we add the 'inUse' class to that iframe element: 
     }).addClass('inUse'); 
}); 

JS Fiddle demo.

Альтернативой иметь только один элемент на странице, скрыть его с помощью CSS:

iframe { 
    display: none; 
} 

И загрузить содержимое в этот единственный со следующим JQuery:

$('a[target]').click(function(e){ 
    // prevents the default click-behaviour of the link: 
    e.preventDefault(); 

    // finds the 'iframe' element with the name of 'showContent': 
    $('iframe[name="showContent"]') 
     // sets its 'src' property equal to the 'href' property of the clicked link: 
     .prop('src', this.href) 
     // shows the 'iframe': 
     .show(); 
}); 

JS Fiddle demo.

Запоздалые редактировать, использовать обычный JavaScript, сделанный на несколько просроченного объяснение, что Jquery не может быть использован:

function contentToIframe() { 
    // getting a reference to the 'iframe' element whose 'name' attribute 
    // is equal to the clicked element's 'target' attribute, using CSS 
    // notation available under document.querySelector() (which returns 
    // only the first element that matches the selector): 
    var iframe = document.querySelector('iframe[name="' + this.target + '"]'), 
     // getting a reference to the current 'display' (inline) style of 
     // the 'iframe' (found above): 
     curDisplay = iframe.style.display; 

    // setting the 'src' property of the 'iframe' equal to the 'href' 
    // of the clicked link: 
    iframe.src = this.href; 

    // if the 'iframe' doesn't have a set 'display' style-property, or 
    // it is not set to 'block': 
    if (!curDisplay || curDisplay !== 'block') { 
     // we set it to 'block' to make it visible: 
     iframe.style.display = 'block'; 
    } 
} 

// getting all the 'a' elements in the document that also have a 'target' 
// attribute: 
var links = document.querySelectorAll('a[target]'); 

// iterating over those link elements: 
for (var i = 0, len = links.length; i < len; i++) { 
    // binding an event-handler to deal with the click event, 
    // which executes the function: 
    links[i].addEventListener('click', contentToIframe); 
} 

JS Fiddle demo.

Final итерация выше (по-прежнему простой JavaScript) подход, который теперь также позволяет прокрутив при щелчке на ссылке для загрузки содержимого:

function contentToIframe() { 
    var iframe = document.querySelector('iframe[name="' + this.target + '"]'), 
     curDisplay = iframe.style.display, 
     // getting a reference to the current position of the 'iframe' element: 
     position = iframe.getBoundingClientRect(); 
    iframe.src = this.href; 
    if (!curDisplay || curDisplay !== 'block') { 
     iframe.style.display = 'block'; 
     // if the 'iframe' wasn't visible it's position would have been 0,0; 
     // so once we've made it visible we re-get its new (now visible) 
     // coordinates: 
     position = iframe.getBoundingClientRect(); 
    } 

    // force the window to scrollTo the current position (x,y) of the 'iframe': 
    window.scrollTo(position.left, position.top); 
} 

var links = document.querySelectorAll('a[target]'); 

for (var i = 0, len = links.length; i < len; i++) { 
    links[i].addEventListener('click', contentToIframe); 
} 

JS Fiddle demo.

Ссылки:

+0

Является ли это jquery или javascript? Извините, я не знаю многого, поэтому не могу сказать. В моем задании мне не разрешено использовать jquery только javascript:/ – ev9604

+0

jQuery * is * JavaScript, это просто библиотека, которая абстрагирует часть сложности родного JavaScript для кросс-браузерного использования. Однако этот ответ полагается на jQuery, да. Я попытался объяснить код в своем самом последнем редактировании, чтобы объяснить, что он делает. –

+2

Wait: вы не можете использовать jQuery? * Могу ли я спросить, почему вы использовали [тег: jquery] в своем вопросе, не ссылаясь на то, что его нельзя использовать? Теги на вопрос должны показывать языки, которые * * или * могут использоваться *, а не те, которые недоступны для вас. –

Смежные вопросы