Javascript 调整 div 元素的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10086693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:48:07  来源:igfitidea点击:

Resize on div element

javascriptjquery

提问by TJR

jQuery has the resize()- event, but it just work with window.

jQuery 有resize()- 事件,但它只适用于窗口。

jQuery(window).resize(function() { /* What ever */ });

This works fine! But when I want to add the event to a div element it doesn't work.

这工作正常!但是当我想将事件添加到 div 元素时它不起作用。

E.g.

例如

jQuery('div').resize(function() { /* What ever */ });

I want to start an callback when the size of a div-element has changed. I don't want to start a resizable - event – just a event to check if the size of a div - element has changed.

我想在 div 元素的大小发生变化时启动回调。我不想启动一个可调整大小的 - 事件 - 只是一个检查 div - 元素大小是否已更改的事件。

Is there any solution to do this?

有没有办法做到这一点?

回答by dxh

DIVdoes not fire a resizeevent, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.

DIV不会触发resize事件,因此您将无法完全执行您编写的代码,但您可以查看监控 DOM 属性

If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.

如果您实际上正在使用诸如可调整大小之类的东西,并且这是改变 div 大小的唯一方法,那么您的调整大小插件可能会实现自己的回调。

回答by Panos Theof

I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.

我只对更改元素宽度时的触发器感兴趣(我不关心高度),所以我创建了一个 jquery 事件,它使用一个不可见的 iframe 元素。

$.event.special.widthChanged = {
  remove: function() {
      $(this).children('iframe.width-changed').remove();
  },
  add: function () {
      var elm = $(this);
      var iframe = elm.children('iframe.width-changed');
      if (!iframe.length) {
          iframe = $('<iframe/>').addClass('width-changed').prependTo(this);
      }
      var oldWidth = elm.width();
      function elmResized() {
          var width = elm.width();
          if (oldWidth != width) {
              elm.trigger('widthChanged', [width, oldWidth]);
              oldWidth = width;
          }
      }

      var timer = 0;
      var ielm = iframe[0];
      (ielm.contentWindow || ielm).onresize = function() {
          clearTimeout(timer);
          timer = setTimeout(elmResized, 20);
      };
  }
}

It requires the following css :

它需要以下 css :

iframe.width-changed {
    width: 100%;
    display: block;
    border: 0;
    height: 0;
    margin: 0;
}

You can see it in action here widthChanged fiddle

你可以在这里看到它在行动中widthChanged fiddle

回答by Akram Kamal Qassas

// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})

(function ($) {

$.fn.sizeChanged = function (handleFunction) {
    var element = this;
    var lastWidth = element.width();
    var lastHeight = element.height();

    setInterval(function () {
        if (lastWidth === element.width()&&lastHeight === element.height())
            return;
        if (typeof (handleFunction) == 'function') {
            handleFunction({ width: lastWidth, height: lastHeight },
                           { width: element.width(), height: element.height() });
            lastWidth = element.width();
            lastHeight = element.height();
        }
    }, 100);


    return element;
};

}(jQuery));

回答by Gavriel

what about this:

那这个呢:

divH = divW = 0;
jQuery(document).ready(function(){
    divW = jQuery("div").width();
    divH = jQuery("div").height();
});
function checkResize(){
    var w = jQuery("div").width();
    var h = jQuery("div").height();
    if (w != divW || h != divH) {
        /*what ever*/
        divH = h;
        divW = w;
    }
}
jQuery(window).resize(checkResize);
var timer = setInterval(checkResize, 1000);

BTW I suggest you to add an id to the div and change the $("div") to $("#yourid"), it's gonna be faster, and it won't break when later you add other divs

顺便说一句,我建议您在 div 中添加一个 id 并将 $("div") 更改为 $("#yourid"),这样会更快,并且以后添加其他 div 时不会中断

回答by DrCord

There is a really nice, easy to use, lightweight (uses native browser events for detection) plugin for both basic JavaScript and for jQuery that was released this year. It performs perfectly:

今年发布了一个非常漂亮、易于使用、轻量级(使用本地浏览器事件进行检测)的基本 JavaScript 和 jQuery 插件。它完美地执行:

https://github.com/sdecima/javascript-detect-element-resize

https://github.com/sdecima/javascript-detect-element-resize

回答by jcubic

I've created jquery plugin jquery.resizeit use resizeObserver if supported or solution based on marcj/css-element-queriesscroll event, no setTimeout/setInterval.

我已经创建了 jquery 插件jquery.resize它使用 resizeObserver 如果支持或基于marcj/css-element-queries滚动事件的解决方案,没有 setTimeout/setInterval。

You use just

你只用

 jQuery('div').on('resize', function() { /* What ever */ });

or as resizer plugin

或作为调整器插件

jQuery('div').resizer(function() { /* What ever */ });

I've created this for jQuery Terminal and extracted into separated repo and npm package, but in a mean time I switched to hidden iframe because I had problems with resize if element was inside iframe. I may update the plugin accordingly. You can look at iframe based resizer plugin in jQuery Terminal source code.

我已经为 jQuery 终端创建了这个并提取到单独的 repo 和 npm 包中,但同时我切换到隐藏的 iframe,因为如果元素在 iframe 内,我在调整大小时遇到​​问题。我可能会相应地更新插件。您可以在 jQuery Terminal source code 中查看基于 iframe 的 resizer 插件

EDIT: new version use iframe and resize on it's window object because the previous solutions was not working when page was inside iframe.

编辑:新版本使用 iframe 并调整其窗口对象的大小,因为当页面位于 iframe 内时,以前的解决方案不起作用。

EDIT2: Because the fallback use iframe you can't use it with form controls or images, you need to add it to the wrapper element.

EDIT2:因为回退使用 iframe,您不能将其与表单控件或图像一起使用,您需要将其添加到包装器元素中。

回答by Nielsen Ramon

Only window is supported yes but you could use a plugin for it: http://benalman.com/projects/jquery-resize-plugin/

只支持窗口是的,但您可以使用插件:http: //benalman.com/projects/jquery-resize-plugin/

回答by Tim Vermaelen

For a google maps integration I was looking for a way to detect when a div has changed in size. Since google maps always require proper dimensions e.g. width and height in order to render properly.

对于谷歌地图集成,我正在寻找一种方法来检测 div 的大小何时发生变化。由于谷歌地图总是需要适当的尺寸,例如宽度和高度才能正确呈现。

The solution I came up with is a delegation of an event, in my case a tab click. This could be a window resize of course, the idea remains the same:

我想出的解决方案是委托一个事件,在我的例子中是一个选项卡点击。当然,这可能是调整窗口大小,想法保持不变:

if (parent.is(':visible')) {
    w = parent.outerWidth(false);
    h = w * mapRatio /*9/16*/;
    this.map.css({ width: w, height: h });
} else {
    this.map.closest('.tab').one('click', function() {
        this.activate();
    }.bind(this));
}

this.mapin this case is my map div. Since my parent is invisible on load, the computed width and height are 0 or don't match. By using .bind(this)I can delegate the script execution (this.activate) to an event (click).

this.map在这种情况下是我的地图 div。由于我的父级在加载时不可见,因此计算出的宽度和高度为 0 或不匹配。通过使用,.bind(this)我可以将脚本执行 ( this.activate)委托给事件 ( click)。

Now I'm confident the same applies for resize events.

现在我相信这同样适用于调整大小事件。

$(window).one('resize', function() {
    this.div.css({ /*whatever*/ });
}.bind(this));

Hope it helps anyone!

希望它可以帮助任何人!

回答by Amranur Rahman

You can change your text or Content or Attribute depend on Screen size: HTML:

您可以根据屏幕大小更改文本或内容或属性:HTML:

<p class="change">Frequently Asked Questions (FAQ)</p>
<p class="change">Frequently Asked Questions </p>

Javascript:

Javascript:

<script>
const changeText = document.querySelector('.change');
function resize() {
  if((window.innerWidth<500)&&(changeText.textContent="Frequently Asked Questions (FAQ)")){
    changeText.textContent="FAQ";
  } else {
    changeText.textContent="Frequently Asked Questions (FAQ)";
  }
}
window.onresize = resize;
</script>

回答by Dillip Kumar Nayak

If you just want to resize the div itself you need to specify that in css style. You need to add overflowand resize property.

如果您只想调整 div 本身的大小,则需要在 css 样式中指定。您需要添加overflowresize 属性

Below is my code snippet

下面是我的代码片段

#div1 {
        width: 90%;
        height: 350px;
        padding: 10px;
        border: 1px solid #aaaaaa;
        overflow: auto;
        resize: both;
    }

<div id="div1">

</div>