jQuery函数使响应方块

时间:2015-07-15 05:48:06

标签: javascript jquery

我尝试编辑此功能

function adjustHeight() {
    var myWidth = $('.equ').width();
    var myString = myWidth + 'px';
    var myHeight = $('.equ').css('height', myString);
    return myHeight;
}

// calls adjustHeight on window load
$(window).load(function() {
    adjustHeight();
});

// calls adjustHeight anytime the browser window is resized
$(window).resize(function() {
    adjustHeight();
});

,使其适用于多个元素,但...... 我失败了。  JsFiddle

3 个答案:

答案 0 :(得分:0)

问题出在each声明中:

$('.equ').each(
    adjustHeight(this);
);

这将立即调用该函数。

使用匿名函数:

$('.equ').each(function() {
    adjustHeight(this);
});

function adjustHeight(e) {
  var myWidth = $(e).width();
  var myString = myWidth + 'px';
  var myHeight = $(e).css('height', myString);
  return myHeight;
}

// calls adjustHeight on window load
$(document).ready(function() {
  $('.equ').each(function() {
    adjustHeight(this);
  });
});

// calls adjustHeight anytime the browser window is resized
$(window).resize(function() {
  $('.equ').each(function() {
    adjustHeight(this);
  });
});
#blue {
  width: 50%;
  /* Just for looks: */
  background-color: cornflowerblue;
  margin: 25px;
}
#red {
  width: 45%;
  /* Just for looks: */
  background-color: red;
  margin: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>


<div id="blue" class="equ"></div>
<div id="red" class="equ"></div>

Demo

答案 1 :(得分:0)

试试这个:

       function adjustHeight(el) {
          $(el).height($(el).width());
        }

        // calls adjustHeight on window load
        $(window).load(function () {
            adjustHeight('.equ');
        });

        // calls adjustHeight anytime the browser window is resized
        $(window).resize(function () {
            adjustHeight('.equ');
        });

答案 2 :(得分:0)

使用each的正确方法是

$('.equ').each(function(){
    adjustHeight(this);
});