skip to Main Content

Please help.

function fontDown() {
  var curSize = parseInt($('.box').css('font-size'));
  curSize--;
  $('.box').css('font-size', curSize + "pt").css('line-height', curSize + "pt");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="fontDown()">button</button>
    
<div class="box" style="font-size: 14pt; line-height: 14pt;">sometext</div>

I expect the font-size to decrease each time I press the button. But, it only increases. Not only that but the font size increases by about 5 or 7 points each time the button is pressed.

3

Answers


  1. use this:
    it easy

    operators +=, *=, -=, /= should be used in jquery

    function fontDown() {
      $('.box')
        .css('font-size', '-=1pt')
        .css('line-height', '-=1pt');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button onclick="fontDown()">button</button>
        
    <div class="box" style="font-size: 14pt; line-height: 14pt;">sometext</div>
    Login or Signup to reply.
  2. .css('font-size') returns a string like 18.6667px which is a px value not pt.

    Changing your code to use px instead will reduce the size as desired.

    function fontDown() {
      var curSize = parseInt($('.box').css('font-size'));
      curSize--;
      $('.box').css('font-size', curSize + "px").css('line-height', curSize + "px");
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button onclick="fontDown()">button</button>
    
    <div class="box" style="font-size: 14pt; line-height: 14pt;">sometext</div>
    Login or Signup to reply.
  3. You need to do a px to pt unit conversion.

    The px to pt ratio is 4/3, so you get a bigger value in px unit, even if you decrease it by one. Then you assign this largest value with a pt unit, which produces a largest font size each time.

    function fontDown()
      {
      let curSize = Math.round( (parseFloat($('.box').css('font-size')) *3) / 4); 
                    // px to pt converssion
      curSize--;
      $('.box').css('font-size', curSize + "pt").css('line-height', curSize + "pt");
      }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button onclick="fontDown()">button</button>
    
    <div class="box" style="font-size: 14pt; line-height: 14pt;">sometext</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search