简体   繁体   中英

Change font-size with jquery if screen size is mobile size

In my web page, I want to change font-size with jquery if screen-size is mobile size. My code is as follow:

<head>
<script type='text/javascript'>
 if(screen.width <= 600){

        $("#para_head").css({"font-size":"12px"});
        $("#para_detail").css({"font-size":"10px"});
}
</script>
<style>
#para_head{
}
#para_detail{
}
</style>
</head>
<body>
<div id="para_head">
    Header
</div>
<div id="para_detail">
    Detail
</div>
</body>

As above code, I can't change the font-size. Where should i fix this. Any idea pls.

Why don't use CSS?

 @media only screen and (max-width: 600px) { #para_head{ font-size: 12px; } #para_detail{ font-size: 10px; } } 
 <div id="para_head"> Para Head </div> <div id="para_detail"> Para Detail </div> 

Have fun :)

I would recommend using a CSS media query rather than jQuery. You will require a lot of jQuery manipulation if your application is big, it will also be harder to maintain and most importantly it will be heavy on the DOM.

Responsive websites are much easier to achieve with CSS as shown below.

@media screen and (max-width: 600px) {
    #para_head {
       font-size: 12px;
    }
}

Demo (Resize the output pane)

https://jsfiddle.net/9351yv7j/

As an additional note I would use the kebab style casing for HTML elements, para-head rather than para_head .

Its better to use media query but if you prefer a jquery solution see below

if ( $(window).width() > 600) {     
  //Add your javascript for large screens here
}
else {

   $("#para_head").css({"font-size":"12px"});
   $("#para_detail").css({"font-size":"10px"});
}

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