编辑:
我在JSFiddle上为此制作了一个演示...但我认为它不会正常工作,因为(window).resize();我还没有用过JSFiddle,所以我觉得我做错了什么。
http://jsfiddle.net/beefchimi/uhw3D/25/
如果有人能帮助解决这个问题,我将非常感激。
我一直在努力寻找使用jQuery复制CSS媒体查询的最佳方法。可以时,在我需要动态计算一个值并将其应用于窗口调整大小的元素时,我必须使用jQuery。
使用以下代码,我可以在每个1像素增量处检查窗口宽度。首先,我想知道从性能上讲是否好,并且是否有一种方式只在我们从断点到断点(480/768/1024)移动时执行函数,而不是沿途的每个像素。
我的问题在于:
我正在检查当前布局中有多少个具有左侧CSS属性的元素:0;然后,我将元素数量乘以240px,并将其应用为容器的高度值。
在720px以下,此元素的高度必须为“自动”。这很好地工作。但是,如果我从320px开始,并达到第一个断点(720px),则会将正确的高度应用于我的容器,但是一旦我达到该断点以上(960px),高度永远不会更新。 我想知道我做错了什么,导致无法计算和应用新值。
$(document).ready(function() {
function checkWidth() {
var windowSize = $(window).width();
var elementCount = $('#casestudy-content article').filter(function() { return $(this).position().left === 0 }).length;
if ( windowSize >= 720 && windowSize <= 959 ) {
console.log("Greater than 720 and less than 960");
console.log(elementCount);
$('#casestudy-content').css('height', elementCount * 240 + 'px');
}
else if ( windowSize >= 960 && windowSize <= 1199 ) {
console.log("Greater than 960 and less than 1200");
console.log(elementCount);
$('#casestudy-content').css('height', elementCount * 240 + 'px');
}
else if ( windowSize >= 1200 ) {
console.log("Greater than or equal to 1200");
console.log(elementCount);
$('#casestudy-content').css('height', elementCount * 240 + 'px');
}
else {
$('#casestudy-content').css('height', 'auto');
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);
});
任何帮助都将不胜感激。
编辑
我发现,如果我在这些元素上删除CSS转换,我的功能就可以完美地工作了。
有趣的是,我的console.log(elementCount)报告了我达到断点时的正确值,所以我认为这应该意味着我不必担心过渡时间,但显然如此。我如何延迟此功能,以便我可以保留过渡效果? 如果我的过渡需要0.2秒,那么我需要延迟函数的触发时间。 请帮忙解决这个问题。