试图实现Fittext.js

时间:2017-10-20 13:06:37

标签: javascript jquery html css

我正在尝试在我的大H1标签上使用jQuery,以便在调整浏览器窗口大小时H1标签中的文本保持不变。

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/text.js"></script>
</head>

<body>

<div class="main">
    <section class="page" id="page1">
        <div class="test">
            <h1>exampletext</h1>

CSS:

.test h1 {
    width:100%;
    text-align:center;
    font-size:250px;
    text-transform:uppercase;
    letter-spacing:5px;
}

JS:

$( document ).ready(function() {
    $("test h1").fitText(1, { minFontSize: '20px', maxFontSize: '250px' });
});

(function( $ ){

  $.fn.fitText = function( kompressor, options ) {

    // Setup options
    var compressor = kompressor || 1,
        settings = $.extend({
          'minFontSize' : Number.NEGATIVE_INFINITY,
          'maxFontSize' : Number.POSITIVE_INFINITY
        }, options);

    return this.each(function(){

      // Store the object
      var $this = $(this);

      // Resizer() resizes items based on the object width divided by the compressor * 10
      var resizer = function () {
        $this.css('font-size', Math.max(Math.min($this.width() / (compressor*10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)));
      };

      // Call once to set.
      resizer();

      // Call on resize. Opera debounces their resize by default.
      $(window).on('resize.fittext orientationchange.fittext', resizer);

    });

  };

})( jQuery );

当我调整浏览器窗口大小时似乎不起作用,我可能做错了什么?

1 个答案:

答案 0 :(得分:1)

这一行

$("test h1").fitText(1, { minFontSize: '20px', maxFontSize: '250px' });

应该是

$(".test h1").fitText(1, { minFontSize: '20px', maxFontSize: '250px' });

您错过了查询选择器中的fullstop

https://jsfiddle.net/craigiswayne/cp5at05y/