[英]Equal heights & media queries
I am puzzled with an equal height problem I am having, you can see in this Fiddle: FIDDLE 我对自己遇到的等高问题感到困惑,您可以在此小提琴中看到: FIDDLE
Code: 码:
$(document).ready(function() {
if ($(window).width() > 768) {
$(window).ready(function() {
var mainHeight = $('.main').height();
$(".block-wrap").height(mainHeight);
});
}else{
$('.block-wrap').css('height','auto');
}
});
$(document).ready(function() {
if ($(window).width() > 768) {
$(window).resize(function() {
var mainHeight = $('.main').height();
$(".block-wrap").height(mainHeight);
});
}else{
$('.block-wrap').css('height','auto');
}
});
Basically I want the 'block-wrap' to get the height of 'main' div. 基本上我想让'block-wrap'达到'main'div的高度。 It works until I use a media query.. the 'block-wrap' still get the height from the 'main' div, while I would like to set it's height on auto, as I tried in the javascript.
它可以一直工作到我使用媒体查询为止。“ block-wrap”仍然从“ main” div中获取高度,而我想在auto上设置其高度,就像我在javascript中尝试的那样。
It works under 768px if I refresh the page, not on resize. 如果刷新页面,它将在768px以下工作,而不是调整大小。
Well, your JavaScript code has numerous problems, including the fact that it was typed twice (?) . 好的,您的JavaScript代码有很多问题,包括两次键入(?)的事实。 Here's what I've changed:
这是我更改的内容:
Removed the duplicate. 删除了重复项。
Wrapped everything in a single $(document).on("ready", callback);
将所有内容包装在一个
$(document).on("ready", callback);
event handler. 事件处理程序。
Added a resize
event listener in order to update your .block-wrap
div
height whenever the user resizes the screen. 添加了
resize
事件监听器,以便在用户调整屏幕大小时更新.block-wrap
div
高度。 Without it, the height
would only change when the page was loaded, but not if the user changes the window size. 没有它,
height
将仅在加载页面时改变,而在用户更改窗口大小时不会改变。
UPDATE: 更新:
resize();
resize();
function after the resize
event handler to resize the .block-wrap
div
after loading the page. resize
事件处理程序之后执行函数以调整.block-wrap
div
大小。 Note that you can achieve this result without relying on JavaScript, by using CSS instead. 请注意,通过使用CSS 可以在不依赖JavaScript的情况下实现此结果。
Here's the final code, optimized and working: 这是经过优化和运行的最终代码:
$(document).ready(function () {
function resize() {
if (window.innerWidth >= 768) {
var mainHeight = $('.main').height();
$(".block-wrap").css({
"height": mainHeight
});
} else {
$('.block-wrap').css({
'height': 'auto'
});
}
}
resize();
$(window).on("resize", function () {
resize();
});
});
And I've adjusted your media query max-width
condition by one pixel: 而且我已经将您的媒体查询
max-width
条件调整了一个像素:
@media only screen and (max-width: 768px) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.