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

标签 javascript html css

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

这是我用来检测手机的 JS: 函数 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() 中尝试过的:

navItems = document.getElementsByTagName('a');

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

但我得到错误:Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

最佳答案

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

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

关于javascript - 使用 Javascript 更改应用于导航菜单项的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15794011/

相关文章:

javascript - 在 AngularJS 的 index.html 上加载动态 CSS

jquery - 单击链接时动画进度条

javascript - 为什么我的文字不是从左到右跳动

javascript - 以编程方式选择剑道网格行

javascript - 我如何检查给定的持续时间 (00 :20:40, 1 :20:40, 00 :00:10) is <20sec, >1 小时 <10 秒

html - Gmail 中的电子邮件缩略图网址更改为 googleusercontent.com

html - 我想在一个 div 中添加两个两个 div

javascript - 如何将 React.Component 放入 CSS 内容属性(在 :before/:after pseudo-elements)?

javascript - 当我单击过滤器菜单时,同位素过滤器图像奇怪的动画和晃动几秒钟

javascript - Internet Explorer 9 中不再触发 ondragstart 事件