簡體   English   中英

使用JavaScript更改應用於導航菜單項的CSS

[英]Change CSS applied to nav menu items using Javascript

我的導航欄中有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:前綴操作中的左側表達式無效

您應該只在CSS中使用媒體查詢來根據瀏覽器大小進行調整。 例如,當瀏覽器小於500px時,將使用以下CSS:

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

使用媒體查詢,您可以根據當前使用站點的設備在CSS中定義樣式。

我認為媒體查詢是實現所需的響應式布局的更好方法:

https://developer.mozilla.org/zh-CN/docs/CSS/Media_queries

請改用媒體查詢。 CSS:

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

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM