首页 > 解决方案 > 按钮 onClick 不能与此 JS 一起使用或以编程方式触发 jquery Resizable Font-size?

问题描述

这是一个可调整大小的 UI 插件 JS,可以通过鼠标单击和拖动正常工作。
它正在font-size用鼠标改变它。意思是,当我从鼠标角div更改宽度或高度时,它会正确更改。但是,当我使用按钮 onClick更改我的宽度或高度时,它不起作用。 我想使用Button 的这个可调整大小的功能。id="chartdiv"font-sizedivid="chartdiv"
font-size

对于这个查询,我已经访问过这个答案:How to trigger jquery Resizable resize programmatically? 但没有font-size功能

我在这里犯了什么错误?

下面是我的代码:

<!DOCTYPE html>
<html>
<head>
    <style>
        .resize{
    font-size: 2.8vh;
    white-space: nowrap;
    color: black;
    background: yellow;
    cursor: move;
    width: 300px;
    height: 130px
}

 .resize:focus {
   width: 500px;  }

    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>

 <button type="button" onClick = "document.getElementById('chartdiv').style.width = '600px';">Click Me!</button>
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/smoothness/jquery-ui.css">
<div class="resize" id="chartdiv">Some name that is very long</div>
    <script type="text/javascript">
        $('.resize').resizable( {
minWidth: 210,
minHeight: 120,
resize: function( event, ui ) {
        // handle fontsize here
        var size = ui.size;
        // something like this change the values according to your requirements
        $( this ).css( 'font-size', ( size.width * size.height ) / 2800 + 'px' ); 
    }
} );
    </script>
</body>
</html>

提前致谢。

标签: javascripthtmljquery

解决方案


下面创建了一个简单的 jQuery 插件函数fontResize(),可以在两个实例中使用

$.fn.fontResize = function() {
  return this.each(function() {
    const $el = $(this);
    $el.css('font-size', ($el.width() * $el.height()) / 2800 + 'px');
  });
}

$('button.do-resize').click(function(){
   $('#chartdiv').width(600).fontResize()// use plugin function
})


$('.resize').resizable({
  minWidth: 210,
  minHeight: 120,
  resize: function(event, ui) {   
    $(this).fontResize();// use plugin function
  }
});
<!DOCTYPE html>
<html>

<head>
  <style>
    .resize {
      font-size: 2.8vh;
      white-space: nowrap;
      color: black;
      background: yellow;
      cursor: move;
      width: 300px;
      height: 130px
    }
    
    .resize:focus {
      width: 500px;
    }
  </style>
  <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>

<body>

  <button class="do-resize"  type="button" >Click Me!</button>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/smoothness/jquery-ui.css">
  <div class="resize" id="chartdiv">Some name that is very long</div>


</body>

</html>


推荐阅读