簡體   English   中英

使用javascript檢測div寬度何時更改

[英]detect when div width is change using javascript

我是 javascript 新手,我想在更改 div 時執行一些操作

在 jquery 中,我使用此代碼

var width = $(window).width();
$(window).resize(function(){
   if($(this).width() != width){
      width = $(this).width();
       console.log(width);
   }
});

但我想用javascript來做,請幫幫我...

您可以像這樣使用 on-resize-event:

 var body = document.getElementsByTagName("BODY")[0]; var width = body.offsetWidth; if (window.addEventListener) { // all browsers except IE before version 9 window.addEventListener ("resize", onResizeEvent, true); } else { if (window.attachEvent) { // IE before version 9 window.attachEvent("onresize", onResizeEvent); } } function onResizeEvent() { bodyElement = document.getElementsByTagName("BODY")[0]; newWidth = bodyElement.offsetWidth; if(newWidth != width){ width = newWidth; console.log(width); } }

訂閱 onresize 事件

window.onresize = functionName

在 Internet Explorer 中,您可以使用“onresize”,在元素 (div) 或主體的大小發生更改時觸發 JavaScript 函數。

但是“onresize”在其他瀏覽器中的工作方式不同。 Mozilla Firefox 僅在調整 body 大小而不是 div 時才會觸發該功能。

<body onresize="myFunction()"> 

將適用於所有瀏覽器

<div onresize="myFunction()">

僅適用於 IE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM