javascript JQuery在窗口调整大小时重新计算css
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15837252/
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
JQuery recalculate css on window resize
提问by topiman
On this site: http://houston.aiga.org/
在这个网站上:http: //houston.aiga.org/
Although the slider is full width / variable on browser window size, the Title of each slider item is always indented to line up with the content.
尽管滑块在浏览器窗口大小上是全宽/可变的,但每个滑块项的标题总是缩进以与内容对齐。
I've tried setting this up: http://jsfiddle.net/topiman/xS7vn/
我试过设置这个:http: //jsfiddle.net/topiman/xS7vn/
$(window).resize(function() {
$('#item').css("padding-left",$(window).width()/2);
});
The function is working but the calculation pushes the item too far in on decreasing window size and too far out on increase.
该函数正在运行,但计算在减小窗口大小时将项目推得太远,而在增加时推得太远。
The line in the working slider example is:
工作滑块示例中的行是:
$('.layout-feature .box-section-image-gallery-controls-title, .layout-feature .box-section-image-gallery-title').css('paddingLeft', 60 + extraSpace/2);
where extraSpace
is the $(window).width()
这里extraSpace
是$(window).width()
Any help gratefully received - thanks in advance
感激地收到任何帮助 - 提前致谢
采纳答案by Luceos
It seems you forgot about the width after all: http://jsfiddle.net/topiman/xS7vn/5/
看来您毕竟忘记了宽度:http: //jsfiddle.net/topiman/xS7vn/5/
This is what I came up with. Stupid thing is the console.log kept giving back a +8 difference which I had to hardcode remove. Is this what you were looking for?
这就是我想出的。愚蠢的是,console.log 不断返回 +8 的差异,我不得不硬编码删除。这就是你要找的吗?
$(window).resize(function() {
var ItemWidth = $(".wrapper").width();
$('#item').width( ItemWidth );
var WindowWidth = $(window).width();
// cannot resize because window is smaller than the wrapper
if( ItemWidth > WindowWidth ) {
var PadWidth = 0;
} else {
var PadWidth = (WindowWidth - ItemWidth)/2 - 8;
}
console.log( ItemWidth + " - " + WindowWidth + " - " + PadWidth );
$('#item').css("margin-left",PadWidth + "px");
});
Update; also check http://jsfiddle.net/xS7vn/8/for the latest update including resizing on page load.
更新; 还要检查http://jsfiddle.net/xS7vn/8/以获取最新更新,包括在页面加载时调整大小。