【问题标题】:jQuery resize window width noconflict modejQuery调整窗口宽度无冲突模式
【发布时间】:2013-12-06 13:57:50
【问题描述】:

尝试将边框宽度更改为窗口的宽度。 让这段代码工作:

jQuery(window).ready(function($) {  

    var windowWidth = $('#portfolio_title .container').outerWidth();

    $('.topBorder').css({'border-right-width':(windowWidth)+'px'});
    $('.btmBorder').css({'border-left-width':(windowWidth)+'px'});

    $(window).resize( function(){
        var windowWidth = $('#portfolio_title .container').outerWidth();
        $('.topBorder').css({'border-right-width':(windowWidth)+'px'});
        $('.btmBorder').css({'border-left-width':(windowWidth)+'px'});
    });
});

但它并不漂亮 尝试像这样优化它:

jQuery(document).ready(myWidth);

jQuery(window).resize(myWidth);

function myWidth($){
    var windowWidth = $('#portfolio_title .container').outerWidth();

    $('.topBorder').css({'border-right-width':(windowWidth)+'px'});
    $('.btmBorder').css({'border-left-width':(windowWidth)+'px'});
};  

文档就绪工作但调整大小没有。 我做错了什么?

【问题讨论】:

    标签: jquery css resize


    【解决方案1】:

    您不能将$ 传递给myWidth 并期望它是jQuery。在myWidth $ 将是一个事件对象。这将为您制作$ jQuery,而无需担心冲突。

    (function($, window, document){
    
      jQuery(document).ready(myWidth);
    
      jQuery(window).resize(myWidth);
    
      function myWidth(){
          var windowWidth = $('#portfolio_title .container').outerWidth();
    
          $('.topBorder').css({'border-right-width':(windowWidth)+'px'});
          $('.btmBorder').css({'border-left-width':(windowWidth)+'px'});
      }; 
    
    })(jQuery, window, document);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      var windowWidth = $('#portfolio_title .container').outerWidth();
      $(function() {  
          $('.topBorder').css({'border-right-width':(windowWidth)+'px'});
          $('.btmBorder').css({'border-left-width':(windowWidth)+'px'});
      
          $(window).resize( function(){
              $('.topBorder').css({'border-right-width':(windowWidth)+'px'});
              $('.btmBorder').css({'border-left-width':(windowWidth)+'px'});
          });
      });
      

      【讨论】:

        【解决方案3】:

        文档就绪处理程序接收 jQuery 对象作为第一个参数,而 resize 处理程序接收事件对象作为参数。

        所以当myWidth 被resize 事件调用时,$ 指的是resize 事件而不是jQuery 对象。

        您可以通过注册调整大小处理程序然后手动触发 dom 准备好的处理程序来修复它,如下所示

        jQuery(function ($) {
            $(window).resize(function () {
                var windowWidth = $('#portfolio_title .container').outerWidth();
                $('.topBorder').css({
                    'border-right-width': (windowWidth) + 'px'
                });
                $('.btmBorder').css({
                    'border-left-width': (windowWidth) + 'px'
                });
            }).resize();
        });
        

        【讨论】:

        • 这不起作用。它进行了初始调整大小,但没有调整窗口大小。
        猜你喜欢
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        • 2012-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多