3

I'm building a responsive site but don't want to just hide elements for smaller screens, I want to remove them completely to reduce load times.

I've got this working so far with

if (window.innerWidth < 768) {
    $('.widescreen').remove();
}

The class .widescreen is added to all elements that are only to be loaded on screens wider than 768px

I then want this to work if a user resizes the browser window (or turns a device 90°) so I tried this:

$(window).resize(function() {
    //small-screen
    if (window.innerWidth < 768) {
        $('.widescreen').remove();
    }
    //end small-screen
});

Which works but only when a window is resized not loaded at the smaller size. Which I guessed would happen.

Is there a way of achieving this so it works both when a page is loaded and when the browser window is resized?

Then, of course, the trick is to add the content back when the window is resized to wider than 768px! But I'll try to figure that one out if the first part is actually possible!!

4

3 に答える 3

6
$(function() {   
 $(window).resize(function() {
        //small-screen
        if (window.innerWidth < 768) {
            $('.widescreen').remove();
        }
        //end small-screen
    }) .resize(); // trigger resize event

})
于 2011-12-21T14:35:35.143 に答える
1

サイズをチェックするコードを関数に配置し、ロード時とサイズ変更時にこの関数を呼び出してみませんか。

function checkSize() {
    //small-screen
    if (window.innerWidth < 768) {
        $('.widescreen').remove();
    }
    //end small-screen
}

checkSize();

$(window).resize(function() {
    checkSize();
});
于 2011-12-21T14:37:38.553 に答える
0

メディア クエリを使用して、これらの部分を非表示にします。

@media all and (max-width: 768px) {
  .widescreen { display: none; }
}

JavaScript を使用したい場合、これはほぼ同じことを行います。

$(function() {   
 $(window).resize(function() {
     $('.widescreen').toggle( window.innerWidth >= 768 )
  }) .resize();
});

どちらの場合も、クライアントはまだ HTML をダウンロードする必要があるため、要素を非表示にする代わりに要素を削除する意味がわかりません。

于 2011-12-21T15:19:46.570 に答える