开发者

Each Click I want to increase the font size using jquery

开发者 https://www.devze.com 2022-12-24 12:26 出处:网络
For each click I want to increase the font size. $(\'#fontplus\').each(function(\'click\') { var fs = $(\'#bod\').css(\'font-size\');

For each click I want to increase the font size.

$('#fontplus').each(function('click') {
    var fs = $('#bod').css('font-size');
    $('#bod').css('font-size',fs+1);

});

<div id开发者_JAVA百科="fontplus">+</div>

Thanks Jean


Well as you have probably discovered, that won't work.

$('#fontplus').click(function() {
  var fs = $('#bod').css('fontSize');

Now you have the current font size. However, what is it? Is it "12px"? Or perhaps it's "1.5em"? Well, assuming you control that, what you'll need to do is take apart the current setting and then put together the new value:

  $('#bod').css('fontSize', (parseInt(fs, 10) + 1) + 'px');
});


Do you actually want them to be able to do this infinitely? I would suggest having 3 or 4 different CSS classes to represent each available font size and manage it with jQuery.

The other examples don't even consider the units used! Points? Pixels? .css("font-size") will return that, so doing a ++ won't work.

$("#fontplus").click(function() {
    switch($("#bod").attr("className"))
    {
        case "large" : /* do nothing */ break;
        case "medium" : $("#bod").removeClass("medium").addClass("large"); break;
        /* do as needed */
    }
});

and I would have each css class look like:

.large { font-size: 1.4em; }
.medium { font-size: 1.2em; }
.normal { font-size: 1em; }
.small { font-size: .8em; }


You need to handle the click event:

$('#fontplus').click(function() {
    var fs = $('#bod').css('font-size');
    $('#bod').css('font-size',fs+1);
});

You will need to set the initial font-size in CSS to an integer value.


   var bod;
   var fontPlus;
   $(document).ready(function() {
      bod = $('#bod');
      fontPlus = $('#fontPlus');
      fontPlus.click(function() {
         var fontSize = bod.css('font-size');
         var fontSizeNum = parseFloat(fontSize, 10);
         bod.css('font-size', fontSizeNum * 1.2);
      });
   });

more info and examples here

0

精彩评论

暂无评论...
验证码 换一张
取 消