开发者

jQuery, toggle button to display plus or minus

开发者 https://www.devze.com 2023-02-15 08:25 出处:网络
How do I toggle toggle the button to display plus or minus? The button enlarges and reduces the text. If text is large...button is minus, if text is small...button is plus etc.

How do I toggle toggle the button to display plus or minus?

The button enlarges and reduces the text. If text is large...button is

minus, if text is small...button is plus etc.

I had some help on this yesterday, I'm still trying to learn jQuery and kind-of-stuck.

Thanks for your help,

<!DOCTYPE html PUBLIC ">
<head>
<script type="text/javascript" src="js/jquery-1.4.min.js"></script>
<script type='text/javascript'>
  var fontSizes = [14, 16]

$(function(){
  $('input').click(function() {
    $('开发者_运维问答p').css('font-size', fontSizes[0] + 'pt');
    fontSizes.reverse();
var currFontSize = ourText.css('fontSize');
var finalNum = parseFloat(currFontSize, 10);
var stringEnding = currFontSize.slice(-2);
if(this.id == 'large') {
finalNum *= 1.2;
}
else if (this.id == 'small'){
finalNum /=1.2;
}
ourText.css('fontSize', finalNum + stringEnding);
});
});
</script>
</head>

<body>
<h2>Toggle Size? </h2>

<!--TOGGLE BUTTON NEEDS TO CHANGE FROM PLUS TO MINUS-->
<input type='button' value='+' id='small' />


<p>My Text!!!</p>
</body>
</html>


Going one stage further from mahesh's answer, use $().toggle(function, function):

var fontSizes = [14, 16];

$(function(){
    $('#PlusMinus').toggle(function() {
        $('#OurText').css('fontSize', fontSizes[1] + 'pt');
        $(this).val("-");
    }, function() {
        $('#OurText').css('fontSize', fontSizes[0] + 'pt');
        $(this).val("+");
    });
});


i don't konw if you need the font size in the js for some reason,
but this would be my take on it:

css:

p.large{
    font-size:1.2em;   
}

input{
    padding:0 5px;   
}

js:

$(function() {

    $('input').toggle(
    function() {
        $(this).val('-');
        $('p').addClass('large');
    }, function() {
        $(this).val('+');
        $('p').removeClass('large');
    });

});

http://jsfiddle.net/e4xyF/


Can't you keep your function small? Like this?

<!DOCTYPE html PUBLIC ">
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type='text/javascript'>
  var fontSizes = [14, 16]

$(function(){
  $('#PlusMinus').click(function() {
  if($(this).val() == "+") {
 $('#OurText').css('fontSize', fontSizes[1] + 'pt');
  $(this).val("-");
  }
  else {
   $('#OurText').css('fontSize', fontSizes[0]+ 'pt');
  $(this).val("+");
  }
});
});
</script>
</head>

<body>
<h2>Toggle Size? </h2>

<!--TOGGLE BUTTON NEEDS TO CHANGE FROM PLUS TO MINUS-->
<input type='button' value='+' id='PlusMinus' />
<p id="OurText">My Text!!!</p>
</body>
</html>
0

精彩评论

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

关注公众号