如果屏幕大小超过900px,则如何允许屏幕大小宽度激活代码

时间:2018-03-08 11:19:10

标签: jquery

<script>
$(function() {

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

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

});
</script>

1 个答案:

答案 0 :(得分:0)

尝试以下代码

<script>
 if ($(window).width() >900) {
$(function() {

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

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

});
}
</script>