简体   繁体   中英

Using positions with jquery for mobile browsers

I want to do something like fixed position, except for all mobile phones.

Like this:

Desktop:

#sidebar{
position:fixed;
width: 200px;
height: auto;
...

And mobile:

#sidebar{
position:absolute;
width: 200px;
height: auto;
...

So i'm wondering, if I use jquery or javascript, something like if mobile: use position absolute, if desktop: use position fixed, it might work.

But I'm not very good at programming javascript etc. I just know html and css. Could anyone help me with what codes I have to use?

Using css3 you can specify for mobile devices using the following.

@media only screen and (max-device-width: 480px)
{
    position:absolute;
}

You can use mordernizr library to detect if the device is a mobile or a desktop. It has a very clean way of doing things.

Basically it will add classes to your html tag based on the device.

no-touch for Desktop and touch for mobile

So based on the classes defined in your HTML you can add the respective CSS definitions .

.no-touch #sidebar{
   position:fixed;
   width: 200px;
   height: auto;
   ...

.touch  #sidebar{
    position:absolute;
    width: 200px;
    height: auto;
    ...

Otherwise you need to check for the navigator.userAgent and check for each and every property to it, based on which you would need to apply the classes. But using the library makes your life a lot more easier, avoids the dirty hacks.

I guess the real question is: how do I detect if the browser is a mobile browser or not? There is the answer: Detecting a mobile browser

You can use JavaScript/jQuery.

This will check if the page is being viewed on a mobile browser and then apply the necessary changes.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
  $("#sidebar").css("position", "absolute");
}

If you prefer a different method, you can check the height and width of the window:

if(window.innerWidth <= 800 && window.innerHeight <= 600) {
  $("#sidebar").css("position", "absolute");
}

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