【问题标题】:jQuery Dynamically Sized margins 2 [closed]jQuery 动态调整边距 2 [关闭]
【发布时间】:2014-10-07 03:38:48
【问题描述】:

我正在使用 jQuery 动态调整垂直边距,我想知道是否可以解决导致页面加载时边距仅调整一次的问题。

    /* PAGE SIZE */
    $(document).ready(function(){
        var WIDTH = $(window).width();
        if(WIDTH > 1420){
            $("ul#menu-content-1.menu").css("margin-top","59px");
            $("div.menu-content-container").css("margin-top","59px")
        } else if(WIDTH < 1420) {
            $("ul#menu-content-1.menu").css("margin-top","-59px");
            $("div.menu-content-container").css("margin-top","-59px");
        }
    });

这是我现有的代码。如何解决这个反复出现的问题,以便每次加载页面并调整窗口大小时,边距都会调整?

【问题讨论】:

  • 使用单个 JavaScript 块来诊断问题有点困难。如果你设置了reducedtest case,也许有人可以帮忙。

标签: javascript jquery html css margin


【解决方案1】:

你可以试试把它放在$(window).load();

 $(window).load(function(){
        var WIDTH = $(window).width();
        if(WIDTH > 1420){
            $("ul#menu-content-1.menu").css("margin-top","59px");
            $("div.menu-content-container").css("margin-top","59px")
        } else if(WIDTH < 1420) {
            $("ul#menu-content-1.menu").css("margin-top","-59px");
            $("div.menu-content-container").css("margin-top","-59px");
        }
    });

【讨论】:

    【解决方案2】:

    .ready().resize() 是使用 .bind() 函数(或 jQuery 1.7+ 中的 .on())的快捷方式。 .resize(function () {}) 映射到 .bind('resize', function () {})

    以下是尽可能使用.on() 的代码外观:

    $(document).on('ready', function() {
    
        $(window).on('resize', function() {
    
             // Stuff in here happens on ready and resize.
    
            var WIDTH = $(window).width();
            if(WIDTH > 1420){
                $("ul#menu-content-1.menu").css("margin-top","59px");
                $("div.menu-content-container").css("margin-top","59px")
            } else if(WIDTH < 1420) {
                $("ul#menu-content-1.menu").css("margin-top","-59px");
                $("div.menu-content-container").css("margin-top","-59px");
            }
    
        }).trigger('resize'); // Trigger resize handlers.       
    
    });//ready
    

    【讨论】:

      【解决方案3】:

      我假设你想在某个时候触发它?

      窗口大小可能调整:jQuery on window resize

      我还建议对上述内容使用 CSS 媒体查询:

      ul #menu-content-1.menu {margin-top: 59px}
      div.menu-content-container {margin-top:59px}
      
      @media (max-width: 1420) 
      { 
          ul #menu-content-1.menu {margin-top: -59px}
          div.menu-content-container {margin-top: -59px}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-14
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        相关资源
        最近更新 更多