jQuery:在特定窗口大小中添加或删除功能

时间:2012-05-23 01:54:19

标签: javascript jquery tinyscrollbar

我是jQuery / JS的新手,我在特定窗口大小中添加或删除功能几乎没有问题。 如果您能查看我的代码并更正它,我将不胜感激。

详细地说,我使用tinyscrollbar插件,我想只出现在特定的窗口大小(让我们说在窗口宽度的650px以上)。

这是我的代码:

<!--****preload latest jQuery and tinyscrollbar plugin, then...****-->

<script type="text/javascript">

function newsScroll() {
    $("#newsScroll").tinyscrollbar();
};

/*
if windows width is less than 650px, remove newsScroll function and
switch DIV ID to "spNewsScroll" and vice versa.
*/
function scrollOnOff(width) {
    width = parseInt(width);
    if (width < 650) {
        $(window).unbind(newsScroll);
        $("#newsScroll").attr('id','spNewsScroll');
    } else {
        $(window).bind(newsScroll);
        $("#spNewsScroll").attr('id','newsScroll');
    }
};

$(function() {
    //get window size as of now.
    scrollOnOff($(this).width());
    $(window).resize(function() {
        scrollOnOff($(this).width());
    });       
});

</script>

1 个答案:

答案 0 :(得分:2)

试试,测试和工作: - )

现场演示: http://jsfiddle.net/oscarj24/fUsnj/21/

function scrollOnOff(width) {
    width = parseInt(width);
    if(width < 650){
        $(window).trigger('newsScroll');
        $('#newsScroll').attr('id','spNewsScroll');
    } else {
        $('.scrollbar').hide();
        $('#spNewsScroll').attr('id','newsScroll');
    }
};

$(function() {

    $(window).bind('newsScroll', function(e) {
        $('.scrollbar').show();
        $('#newsScroll').tinyscrollbar();
    });

    var screenWidth = $(this).width();
    scrollOnOff(screenWidth);

    $(window).on("resize", function(event){
        var w = $(this).width();
        scrollOnOff(w);                
    });

});