【问题标题】:Loop the script for get the correspondent of the element循环脚本以获取元素的对应对象
【发布时间】:2021-11-01 11:28:00
【问题描述】:

我想减小文本字体大小,直到文本具有一定高度(在示例中为 54 像素)。 但是脚本只执行了 1 次(仅通过负载读取高度,不再读取)。我不能循环这个。

https://jsfiddle.net/Nata_Hamster/zpvhow68/

$(document).ready(function() {
  let fact1 = $('div');
  let fact1_h = fact1.height();
  let fact_fs = parseInt($('div').css('font-size'));
  alert(fact_fs);

  if (fact1_h > 54) {
    fact_fs -= 1;
    fact1.css({
      'font-size': fact_fs + 'px'
    });
    alert(fact_fs);
    fact_fs = parseInt($('div').css('font-size'));
  }
});
div {
  width: 200px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. </div>

【问题讨论】:

  • 在单独的函数中编写代码并返回高度并在循环中调用它直到您想要的高度

标签: javascript loops


【解决方案1】:

你确实需要循环,但你也需要给界面时间来调整

$(function() {
  const fact1 = $('div');
  const tID = setInterval(function() {
    let fact1_h = fact1.height();
    let fact_fs = parseInt($('div').css('font-size'));
    if (fact1_h <= 54) {
      clearInterval(tID)
      return
    }
    fact_fs -= 1;
    fact1.css({
      'font-size': fact_fs + 'px'
    });
  }, 10);
})
div {
  width: 200px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. </div>

【讨论】:

    【解决方案2】:

    您可以使用while 语句,只要给定条件为真,它就会执行给定语句。

    $(document).ready(function() {
      let fact1 = $('div');
      let fact1_h = fact1.height();
      let fact_fs = parseInt($('div').css('font-size'));
      console.log('Initial font size', fact_fs);
    
      while (fact1_h > 54) {
        fact_fs -= 1;
        fact1.css({
          'font-size': fact_fs + 'px'
        });
        fact1_h = fact1.height();
        console.log('New Font - ', fact_fs);
        console.log('New Height - ', fact1_h);
      }
    });
    div {
      width: 200px;
      padding-left: 20px;
      padding-right: 20px;
      font-size: 20px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div>JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. </div>

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      相关资源
      最近更新 更多