简体   繁体   中英

Change an a tag attribute in JavaScript based on screen width

I was trying to change the attribute of an a tag using media queries but I found out that media with a hyperlink is purely advisory. So, the alternative is to use JavaScript but I seem to be having trouble getting the screen.width to work.

JavaScript:

function adjustHeight(){
    var actual_width=screen.width;
    alert("width: " + actual_width);
    if(actual_width < 1281) {
        var h1= document.getElementById('procsLink').getAttribute('font-size');
        alert("font-size: " + h1);
        h1 = 35px;
        document.getElementById('procsLink').setAttribute('<font></font>-size',h1)
    }
return false;
}

Here is my Jsfiddle of the code: http://jsfiddle.net/Arandolph01/2DVv9/

Note: I know there is a way to have the link still appear after 'click' so you can see the changed attribute. (Not sure how)

What do I need to do to get the JavaScript to recognize the screen size? Is my a tag correct?

Thank you.

Here is the problem, there is no id on that anchor tag so adjust your html like this: - added id to the anchor tag - removed the actual link so you can see the a tag change font size - removed the semicolon in the onclick

<span id="sigs" style="display: block;">
    <li >
        <a id="procsLink" href="#" onclick="adjustHeight()" class="sigsLink" >Manage Signatures</a>
    </li>
</span>

Than your css like this:

#procsLink{
    font-size: 14px;
}

And your JS like this:

function adjustHeight(){

    var actual_width = window.innerWidth;

    if(actual_width < 1281) {
        var h1 = document.getElementById('procsLink');
        var newFontSize = '35px';
        h1.style.fontSize = newFontSize;
    }

}
function adjustHeight(){

    var actual_width  =screen.width;
    alert("width: " + actual_width);
    if(actual_width < 1281) {
        var h1 = document.getElementById('procsLink').getAttribute('font-size');
        alert("font-size: " + h1);
        h1 = "35px";
        document.getElementById('procsLink').setAttribute('font-size',h1)
    }
    return false;
}

Add quote to 35px ;)

You missed the semicolon after:

document.getElementById('procsLink').setAttribute('<font></font>-size',h1)

And add quote to 35px.

Well your code is working fine now, I updated your fiddle

function adjustHeight(){
   var actual_width = screen.width;
   alert("width: " + actual_width + "px");
   if(actual_width < 1281) {
      var h1 = document.getElementById('procsLink').getAttribute('font-size');
      alert("font-size: " + h1);
      h1 = "35px";
      document.getElementById('procsLink').setAttribute('<font></font>-size',h1);
   }
   return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM