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

时间:2013-04-03 17:25:33

标签: javascript html 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 

  }
}

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;
}

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> 

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

navItems = document.getElementsByTagName('a');

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

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

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

使用媒体查询,您可以根据当前使用您网站的设备在css中定义样式。

我认为媒体查询是实现您寻求的响应式布局的更好方法:

https://developer.mozilla.org/en-US/docs/CSS/Media_queries

答案 2 :(得分:3)

请改用媒体查询。 CSS:

@media all and (max-width: 320px) {

    #topnav ul li a {
        width:100%;
    }

}