简体   繁体   中英

JQuery: How to detect mobile width and change my css to it's with using jquery?

How to detect mobile width and change my css to it's current window width using jquery?

For Example

.page {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    float: left;
    margin: 40px 0;
    max-width: 480px;
    min-height: 720px;
    height: auto;
    min-width: 360px;
    padding: 10px;
    width: 100%;
}

and then I have this function but I am not sure if it's really working.

function responsiveFn() {
    width = $(window).width();
    document.getElementById('widthID').innerHTML = width;
    jQuery('.page').css({
        max-width: width
    });
}

Thanks for the answer in advance! :)

No need of using Javascript/jQuery, check the below points.

Suggestions:

  1. Use width in percentages so, when resized it'll auto adjust
  2. Use media queries for resolution specific styles
  3. When setting properties from Javascript, use quotes around property name or use camelcase. Ex. maxWidth, or 'max-width'

Example:

@media (max-width: 600px) {
    .page {
        width: 200px;
    }
}
  1. Create separate CSS file for various resolutions and load them for such resolutions

Example:

<!-- CSS media query on a link element -->
<link rel="stylesheet" media="(max-width: 600px)" href="mobile.css" />

Update

If you still want to use Javascript, call your function on window resize event.

window.onresize = responsiveFn;

Use max-width in quotes

jQuery('.page').css('max-width', width);

Please use media query for all the elements as per your requirement example

@media screen and (min-width: 320px) and (max-width:580px) {
    .btn-default {
        float: none;
        max-width: 100%;}
    .textcenter {
        text-align: center;
    }
}

As button and textcenter class will be changed with the mentioned property

Thanks

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