jquery在调整大小时响应不起作用

jquery responsive on resize not working

本文关键字:响应 不起作用 小时 调整 jquery      更新时间:2023-09-26

我想检查(调整大小时)窗口宽度,然后加载脚本的一个特殊部分。当浏览器窗口是<500px宽度我想滚动到div的顶部(当点击菜单链接时),当浏览器窗口>500px时,我想滚动至div的垂直中间。它在某种程度上起作用,但速度慢而且有缺陷。

首先我创建了"调整大小"函数然后我检查浏览器宽度

(function($){
    // on load
    $(window).resize(function(){
        var current_width = $(window).width(); //check width
            $('.go').click(function (e) {
                if(current_width > 700){ // when min-width 700px than go to center of DIV
                    e.preventDefault();
                    var $box = $('.box').eq($(this).data('rel') - 1);
                    $('html, body').animate({
                        scrollTop: $box.offset().top - ($(window).height() - $box.outerHeight(true)) / 2 // scroll to verticall middle of div
                    }, 200);
                }

                else if(current_width < 700){ // when max-width 700px than go to top of DIV
                    e.preventDefault();
                    var $box = $('.box').eq($(this).data('rel') - 1);
                    $('html, body').animate({
                        scrollTop: $box.offset().top + 0 // scroll to top of div
                    }, 200);
            }
        });
    });
})(jQuery);

当id使用"文档就绪"时,一切都很好。。。但是"调整文档大小"会带来问题。

在这里摆弄

更新-让它以这种方式工作:

$(".go").click(function(){
            if ($(window).width() < 800) { // if window smaller than 800px    
                var $box = $('.box').eq($(this).data('rel') - 1);
                $('html, body').animate({
                    scrollTop: $box.offset().top - 0
                }, 200);
            }
            if ($(window).width() > 800) { // if window bigger than  800px
                var $box = $('.box').eq($(this).data('rel') - 1);
                $('html, body').animate({
                    scrollTop: $box.offset().top - ($(window).height() - $box.outerHeight(true)) / 2
                }, 200);
            }
        });

最好附加这样的事件处理程序:

var resizeTimeout; //the timeout prevents triggering the resize event more than once
$(function () {
    $(window).resize(function () {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(resize, 500);
    });
    $('.go').click(function (e) {
    });
});
function resize() {
    if ($(window).width() > 700) {
    } else {
    }
}

也许是个坏主意,但你可以在css中尝试这样的东西:

@media screen and (min-width: 480px){
    $("body").css({"position":"absolute", "top":"12px", "left":"12px"}); //Set your x and y 
}
@media screen and (min-width: 768px){
    $("body").css({"position":"absolute", "top":"22px", "left":"22px"}); //Set other stuff
}

无需javascript:)

PS:未测试!