前端開發 | 如何使用jQuery resize event套件

在原始的JS語法中,只有瀏覽器的window物件可以觸發resize事件,如果想要知道其他元素的大小尺寸有沒有改變,只能自行去檢查元素的寬度及高度。若是想要讓其他元素也能觸發resize事件,就要定期去檢查元素的大小尺寸,一旦發現有改變、就丟出一個resize的事件出來。jQuery resize event 就是這樣子的一個套件。
從這篇文章你會知道:
- 如何使用jQuery resize event
使用jQuery resize event將元素綁定resize事件之後,jQuery resize event 會啟動一個內部的循環、定期檢查元素的大小變化,並在發現變化之後觸發resize事件。這個時間的周期是250毫秒。
使用範例
jQuery resize event的使用非常的簡單,只需要使用 .resize() 或 .bind( “resize", fn ) 或 .trigger( “resize" ),就跟對window對象使用的方式一樣。
// 這是原始的window觸發resize的方法
$(window).resize(function(e){
// do something when the window resizes
});
// 套用jQuery resize event之後,我們也可以讓元素這樣子來觸發resize事件
$("#unicorns").resize(function(e){
// do something when #unicorns element resizes
});
// 還可以這樣子用
$("span.rainbows").bind( "resize.rainbows", function(e){
// do something when any span.rainbows element resizes
});
實際操作
載入jQuery 及 jQuery resize event
<script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript" src="jquery.ba-resize.js"></script>
HTML
<div id="container" class="container">
<h3>jQuery resize event Testing</h3>
<div class="container">
<div class="info">N/A</div>
<textarea class="test">Drag to resize in Safari or Chrome. Notice that the info box updates slowly, because the resize event is *not* being triggered manually. (How could it? You're dragging a proprietary browser control!)</textarea>
</div>
</div>
Javascript
$(function(){
// Bind the resize event. When any test element's size changes, update its
// corresponding info div.
$('.test').resize(function(){
var elem = $(this);
// Update the info div width and height - replace this with your own code
// to do something useful!
elem.closest('.container').find('.info')
.text( this.tagName + ' width: ' + elem.width() + ', height: ' + elem.height() );
});
// Update all info divs immediately.
$('.test').resize();
// Add text after inline "add text" links.
$('.add_text').click(function(e){
e.preventDefault();
$(this).parent().append( ' Adding some more text, to grow the parent container!' );
});
// Resize manually when the link is clicked, but only for the first paragraph.
$('.add_text:first').click(function(){
$(this).parent().resize();
});
});
將上面的HTML及Javascript 放進您網頁中適合的位置、你就可以得到底下圖片展示的效果

〖參考資料來源〗:
https://benalman.com/projects/jquery-resize-plugin/
https://benalman.com/code/projects/jquery-resize/examples/resize/
CodePen示範:https://codepen.io/ellen-shih/pen/xxPJemm
我要留言