Использование Javascript для изменения текста ссылки на ссылку при изменении ширины окна - PullRequest
0 голосов
/ 18 января 2012

Я пытаюсь создать простой javascript, который изменит содержимое якорной ссылки, когда окно браузера станет меньше определенной ширины, и вернет его обратно, если оно превысит указанную ширину.

HTML:

<footer id="about" style="">
    <ul id="aboutFooter" style="">
        <li><a href="http://twitter.com/whatever" id="twitter">OUR 140-CHARACTER THOUGHTS</a></li>
        <li><a href="mailto:whatever@gmail.com" id="email">EMAIL US AT WHATEVER@GMAIL.COM</a></li>
        <li><a href="#" id="middleMan">OR KEEP THINGS SIMPLE AND HIT "NEXT"</a></li>
    </ul>
</footer>

JAVASCRIPT:

 var mq = window.matchMedia( "(min-width: 1074px)" ); 
        if (mq.matches) { 
            document.getElementById("email").firstChild.nodeValue = "EMAIL US AT whatever@gmail.com";
            document.getElementById("twitter").firstChild.nodeValue = "OUR 140-CHARACTER THOUGHTS";
        }  

        else {
            document.getElementById("email").firstChild.nodeValue = "EMAIL";
            document.getElementById("twitter").firstChild.nodeValue = "TWITTER";
        }

В данный момент он вообще не работает - остается только начальные значения для каждого элемента. У меня на той же странице работает jQuery, возможно ли, что они мешают друг другу?

1 Ответ

2 голосов
/ 18 января 2012

Вы должны добавить прослушиватель, чтобы он обновлялся при изменении состояния.Пример из http://dbaron.org/log/20110422-matchMedia (это копирование и вставка, а не мой код):

function setup_for_width(mql) {
  if (mql.matches) {
    // The screen width is 400px or wider.  Set up or change things
    // appropriately.
  } else {
    // The screen width is less than 400px.  Set up or change things
    // appropriately.
  }
}

var width_mql = window.matchMedia("(min-width: 400px)");
// Add a listener for when the result changes
width_mql.addListener(setup_for_width);
// And share the same code to set things up with our current state.
setup_for_width(width_mql);

Просто измените 400px в их примере на 1074px, заполните пробелы (где комментарии), и это должно работать на вас.Как это:

function setup_for_width(mql) {
  if (mql.matches) {
    document.getElementById("email").firstChild.nodeValue = "EMAIL US AT whatever@gmail.com";
    document.getElementById("twitter").firstChild.nodeValue = "OUR 140-CHARACTER THOUGHTS";
  } else {
    document.getElementById("email").firstChild.nodeValue = "EMAIL";
    document.getElementById("twitter").firstChild.nodeValue = "TWITTER";
  }
}

var width_mql = window.matchMedia("(min-width: 1074px)");
// Add a listener for when the result changes
width_mql.addListener(setup_for_width);
// And share the same code to set things up with our current state.
setup_for_width(width_mql);
...