在 Javascript 中强制 dom 重新加载/调整大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11005346/
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
Force dom reload/resize in Javascript
提问by typeoneerror
I have a sidebar in my app that can be hidden/shown via a toggle button. It simply toggles a class on "body" that adds some margin left to the content area and hides/shows the sidebar. Trouble is that the content area isn't resizing its child content when this is toggled. Once I adjust the size of the browser, the content area adjusts to fit the content, but I need it to do this after the toggle without the need to resize the window. Is there a way to trigger an element size refresh or dom refresh to solve this issue? Using Chrome 19.x.
我的应用程序中有一个侧边栏,可以通过切换按钮隐藏/显示。它只是在“body”上切换一个类,为内容区域添加一些左边距并隐藏/显示侧边栏。问题是当切换时内容区域没有调整其子内容的大小。一旦我调整了浏览器的大小,内容区域就会调整以适应内容,但我需要在切换后执行此操作而无需调整窗口大小。有没有办法触发元素大小刷新或dom刷新来解决这个问题?使用 Chrome 19.x。
$('#sidebar-toggle').click(function(event) {
event.preventDefault();
$('body').toggleClass('with-sidebar-left');
});
Edit:Seems like it might be a Webkit issue. Works fine in Firefox.
编辑:似乎这可能是 Webkit 问题。在 Firefox 中运行良好。
Edit 2:Set up a simplified build at the following location:
编辑 2:在以下位置设置简化构建:
https://dl.dropbox.com/u/189605/misc/build-test/grid.html
https://dl.dropbox.com/u/189605/misc/build-test/grid.html
You can see the boxes are float: left and when you minimize the sidebar using the little arrow button, it should adjust the right so more boxes will fit. In Webkit, you have to resize the browser for it to realize it's got more space. Works in Firefox.
你可以看到盒子是浮动的:左边,当你使用小箭头按钮最小化侧边栏时,它应该向右调整,以便更多的盒子适合。在 Webkit 中,您必须调整浏览器的大小,才能意识到它有更多空间。在 Firefox 中工作。
回答by billythetalented
you could just trigger a resize in your click handler, eg:
您可以在点击处理程序中触发调整大小,例如:
$(window).trigger('resize')
回答by thirtydot
The workaround from my answer hereworks for your situation.
我在此处回答的解决方法适用于您的情况。
Here's a quick demo: http://jsbin.com/amakex
这是一个快速演示:http: //jsbin.com/amakex
It works in both Chrome and Safari (unsurprisingly, your original demo also didn't work in Safari).
它适用于 Chrome 和 Safari(不出所料,您的原始演示也不适用于 Safari)。
回答by Ash
you said-"but I need it to do this after the toggle without the need to resize the window".you can use jquery callback to do that
你说 - “但我需要它在切换后执行此操作而无需调整窗口大小”。你可以使用 jquery 回调来做到这一点