按钮单击不使用此JS或以编程方式触发jquery可调整字体大小



这里有一个可调整大小的UI插件JS,它可以很好地使用鼠标点击&拖动
它正在用鼠标更改为font-size。也就是说,当我从鼠标角使用id="chartdiv"更改div的宽度或高度时,它将正确更改font-size。但是,当我用id="chartdiv"按钮单击更改div的宽度或高度时,它就不起作用了
我想使用按钮中的此font-size可调整大小的功能。

对于这个查询,我已经访问了这个答案:如何通过编程触发jquery Resizable resize?但没有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>

提前谢谢。

下面创建了一个简单的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>

<button type="button" onClick = "ResizeWithButton();">Click Me!</button>
function ResizeWithButton(){
var x = document.getElementById('chartdiv');
x.style.width = '600px';
var rect = x.getBoundingClientRect();
x.style.fontSize = `${(rect.width * rect.height)/2800}px`;
}

最新更新