【问题标题】:Why this resize handler is not working? [duplicate]为什么这个调整大小处理程序不起作用? [复制]
【发布时间】:2017-05-02 21:46:46
【问题描述】:

https://jsfiddle.net/57org2ve/2/

HTML:

<div id="at" style="width:100%;background:red">
This is a div, you can click on me or resize me. 
</div>

JavaScript:

$('#at').resize(function(){alert(1)})
$('#at').click(function(){alert(2)})

【问题讨论】:

  • 我知道 $(window) 仅用于调整大小,但在您的情况下,元素想要调整事件的大小。我也在寻找解决方案
  • 我相信 resize 事件只能在 window 对象上使用,所以你需要使用 $(window).resize() 但它看起来更像是你想要在用户直接更改元素的大小时触发一个事件?
  • 是的,正是我想要在元素上调整大小事件。
  • raw.githubusercontent.com/cowboy/jquery-resize/v1.1/… 发现了这个技巧,但它是 6 年前的......我不知道是否有任何更好的方法......
  • 你能告诉我它是如何工作的吗?

标签: jquery


【解决方案1】:

我觉得你需要参考这个链接

http://marcj.github.io/css-element-queries/

我刚刚检查了这个js,这对我有用,下载这个文件并检查它,希望这对你有帮助

var element = document.getElementById('at');
new ResizeSensor(element, function() {
   console.log('Changed to ' + element.clientWidth);
});

【讨论】:

  • 为我觉得有趣的事情点赞。
【解决方案2】:

如果元素的宽度发生了变化,也许可以使用一个小函数来检查 onresize。调整浏览器大小并查看控制台日志结果。

$(window).resize(function(){

  var obj = $('#at')[0];
  if(detectResize(obj)) console.log('resize detected');

});


function detectResize(getObject){
  var getWidth = getObject.getBoundingClientRect().width;
  if(getObject.currentWidth===getWidth){
    return false;
   } else {
     getObject.currentWidth = getWidth;
     return true;
   }
}
#at{
  width:100%;
  max-width:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="at" style="background:red">
This is a div, you can click on me or resize me. 
</div>

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    相关资源
    最近更新 更多