简体   繁体   中英

run jquery only on certain screen size?

var $sidebar   = $("#sidebar"), 
                $window    = $(window),
                offset     = $sidebar.offset(),
                topPadding = 15;

            $window.scroll(function() {
                if ($window.scrollTop() > offset.top) {
                    $sidebar.stop().animate({
                        marginTop: $window.scrollTop() - offset.top + topPadding
                    });
                } else {
                    $sidebar.stop().animate({
                        marginTop: 0
                    });
                }
            });

I'm using this script to enable sticky sidebar when scrolling thru a page but i want the sidebar to stay in a relative position when the screen size changes from desktop to mobile.

在此处输入图片说明

so when in mobile view, i want it to stay in a fixed relative psoition without the auto scrolling. like this:

在此处输入图片说明

It's not working properly with the script that i wrote. Any advice?

To get the width of the window you can do

 var w = window.innerWidth;

So you can create some sort of conditional before you run the jquery for a certain screen size.

if (window.innerWidth > 1200) // dont run jquery 

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