使用Javascript更改应用于导航菜单项的CSS

Bat*_*man 0 html javascript css html5 css3

我的导航栏中有4个页面链接.我想在使用移动浏览器时调整它们的大小.

这是我检测移动设备的JS:function detectmob(){

 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    alert('This be a mobile browser');
    style3(); //a function which applies other CSS changes to my page
    //Trying to figure out how I'd change the width of my a elements within my nav to 100% width 

  }
}
Run Code Online (Sandbox Code Playgroud)

CSS:

#topnav ul li a {
    width: 175px; //I'd like to change this to 100% using JS based on above condition
    height: 40px;
    line-height: 53px;
    border-bottom: 4px solid #636393;
    padding:0px;
    color: #fff;
    font-size:18px;
    font-weight:lighter;
    text-align:center;
    text-decoration: none;
    display: block;
    -webkit-transition: .1s all linear;
    -moz-transition: .1s all linear;
    transition: .1s all linear;
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<nav id="topnav">
    <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="video.html">Trailers</a></li>
        <li id='adminPage'><a href="admin.html">Admin</a></li>
    </ul>
</nav> 
Run Code Online (Sandbox Code Playgroud)

这是我在detectmob()中尝试的,如果为true:

navItems = document.getElementsByTagName('a');

 for(var i =0; i < navItems.length;++1){
navItems[1].style.width = "100%"; 
    }
Run Code Online (Sandbox Code Playgroud)

但我得到错误:未捕获的ReferenceError:前缀操作中的左侧表达式无效

dsu*_*ndy 5

您应该只在css中使用媒体查询来根据浏览器大小进行调整.例如,当浏览器小于500px时,将使用以下CSS:

@media screen and (max-width : 500px) {
    /* Styles for less than 500px */
}
Run Code Online (Sandbox Code Playgroud)