我有一个流畅的网格布局.我需要一些列(不太必要 – 比如Twitter更新)在较小的分辨率上为“HIDDEN”,在点击其标题时为“SHOWN”. 这是我到目前为止所拥有的: HTML div id="wrapper" div class="
这是我到目前为止所拥有的:
HTML
<div id="wrapper"> <div class="toggle"> <h2>Heading</h2> This content is visible always </div> <div class="toggle-small"> <h2 class="toggle-small-heading">Heading</h2> <div class="toggle-small-content"> This content is hidden on max-width 600px. You can reveal it by clicking the heading. </div> </div> <div class="toggle-small"> <h2 class="toggle-small-heading">Heading</h2> <div class="toggle-small-content"> This content is hidden on max-width 600px. You can reveal it by clicking the heading. </div> </div> </div>
JQUERY
// D E F I N E T H E F U N C T I O N function ToggleSmall () { // CONDITIONALS // Clickable heading var ToggleSmallVar = $('#wrapper').find('.toggle-small-heading'); // Content to toggle var ToggleSmallCol = $('#wrapper').find('.toggle-small-content'); // FUNCTION // Content to toggle - hide it to be shown on click $(ToggleSmallCol).addClass('none'); // Toggle function $(ToggleSmallVar).click(function () { // Find col to toggle var ToggleSmallColTarget = $(this).closest('.toggle-small-section').find('.toggle-small-col'); // Toggle the DIV $(ToggleSmallColTarget).slideToggle('slow'); }); } // C A L L T H E F U N C T I O N $(document).ready(function () { if ($(window).width() < 681) { ToggleSmall(); } });
它适用于加载,但我尝试使它在窗口大小调整上“响应”工作:对小于681的分辨率执行ToggleSmall()函数并在较大的分辨率上停止它.
我试图在“调整大小”事件(例如jQuery as Media Queries on resize)上绑定该函数,但由于某种原因“切换”执行3-4次(文档多次“准备好”?).
我发现了一些其他的解决方案 – 主要是为了定义一个变量 – 但到目前为止还没有.我也是一个jQuery新手,所以也许我错过了一些东西. :) 有任何想法吗?
有人建议使用’timer’事件监听器来调节javascript的行为和处理从Curt Howard example开始复制:
var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); $(function() { var pause = 100; // will only process code within delay(function() { ... }) every 100ms. $(window).resize(function() { delay(function() { var width = $(window).width(); if( width >= 768 && width <= 959 ) { // code for tablet view } else if( width >= 480 && width <= 767 ) { // code for mobile landscape } else if( width <= 479 ) { // code for mobile portrait } }, pause ); }); $(window).resize(); });