【问题标题】:How to run this jquery code only before and after particular screen size?如何仅在特定屏幕尺寸之前和之后运行此 jquery 代码?
【发布时间】:2011-12-25 23:50:52
【问题描述】:

我有这个 jQuery 代码

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$( document ).ready( function() {
                var $body = $('body'); //Cache this for performance

                var setBodyScale = function() {
                    var scaleFactor = 0.35,
                        scaleSource = $body.width(),
                        maxScale = 600,
                        minScale = 30;

                    var fontSize = scaleSource * scaleFactor; //Multiply the width of the body by the scaling factor:

                    if (fontSize > maxScale) fontSize = maxScale;
                    if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums

                    $('body').css('font-size', fontSize + '%');
                }

                $(window).resize(function(){
                    setBodyScale();
                });

                //Fire it when the page first loads:
                setBodyScale();
            });
</script>

但我只想在@media only screen and (min-width : 1025px) and (max-width : 2048px) 不在那之后也不在那之前激活这个 jQuery 代码。

在 1024 像素之前和 2048 像素之后,脚本不应执行任何操作。

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

    我认为不可能从 javascript 中获取 @media 配置。

    您可以获取文档的宽度并检查其值:

    var docWidth = $(document).width();
    if (docWidth > 1024 && docWidth < 2048) {
        // execute your function
    }
    

    我不知道是否需要,但是如果用户调整窗口大小,您可能还需要绑定到调整大小事件:

    $(window).resize(function(event) {
        //execute your function
    });
    

    d.

    【讨论】:

      【解决方案2】:

      使用 jquery 调整大小事件:

      $(window).resize(function() {
      
        // Check here the width
        width = $(document).width();
      
        if (width > 1024 && width < 2048) {
      
            // do your code
         }
      });
      

      我认为你可以用这个做你想做的事

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多