jQuery:在特定窗口大小中添加或删除函数

jQuery: Add or Remove function in a specific window size

本文关键字:添加 删除 函数 窗口大小 jQuery      更新时间:2023-09-26

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

详细地说,我使用微小的滚动条插件,我只想以特定的窗口大小出现(假设窗口宽度高于 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>

试试这个,经过测试并工作:-(

现场演示: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);                
    });
});