【问题标题】:JQuery using single function instead of multipleJQuery 使用单个函数而不是多个函数
【发布时间】:2016-08-20 10:08:09
【问题描述】:

您好,我想简化这 4 个类似的功能。只有选择器最终发生了变化。请问我该怎么做?非常感谢!

$('.box.standard .title').css({
                'position' : 'absolute',
                'left' : '50%',
                'top' : '50%',
                'margin-left' : -$('.box.standard .title').outerWidth()/2,
                'margin-top' : -$('.box.standard .title').outerHeight()/2
            });

            $('.box.large .title').css({
                'position' : 'absolute',
                'left' : '50%',
                'top' : '50%',
                'margin-left' : -$('.box.large .title').outerWidth()/2,
                'margin-top' : -$('.box.large .title').outerHeight()/2
            });

            $('.box.wide .title').css({
                'position' : 'absolute',
                'left' : '50%',
                'top' : '50%',
                'margin-left' : -$('.box.wide .title').outerWidth()/2,
                'margin-top' : -$('.box.wide .title').outerHeight()/2
            });

【问题讨论】:

    标签: jquery centering simplify


    【解决方案1】:

    让它成为一个函数,并在你喜欢的时候使用它:

    function myFunction(cssClasses){  
    
      $(cssClasses).css({
                        'position' : 'absolute',
                        'left' : '50%',
                        'top' : '50%',
                        'margin-left' : -$('.box.wide .title').outerWidth()/2,
                        'margin-top' : -$('.box.wide .title').outerHeight()/2
                    });
    
    }
    
    myFunction('.box.standard .title');
    myFunction('.box.large .title');
    myFunction('.box.wide .title');
    

    【讨论】:

      【解决方案2】:

      试试:

      var myArray = ['.box.standard', '.box.large', '.box.wide'];
      
      for (var i of myArray) {
      
        $(i+' .title').css({
                      'position' : 'absolute',
                      'left' : '50%',
                      'top' : '50%',
                      'margin-left' : -$(i+' .title').outerWidth()/2,
                      'margin-top' : -$(i+' .title').outerHeight()/2
                  });
      
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用一个函数来帮助您访问this,它指的是选定的元素。应该这样做:

               $('.box.standard .title, .box.large .title, .box.wide .title').css({
                    'position' : 'absolute',
                    'left' : '50%',
                    'top' : '50%',
                    'margin-left' : function() {
                        return -$(this).outerWidth()/2;
                    },
                    'margin-top' : function() {
                        return -$(this).outerHeight()/2;
                    }
                });
        

        【讨论】:

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