2015-01-23 5 views
1

JavaScript에 대해 거의 알지 못해서 제 질문이 맞는지 확실하지 않습니다. 그러나 내 요점은 화면의 너비에 따라 스크립트의 특정 값을 변경하기 위해 동일한 미디어 쿼리 원칙을 적용하는 방법입니다.JavaScript에서 미디어 쿼리를 사용하는 방법

다음 예에서는 헤더 보정을 위해 -100px의 음수 스크롤과 함께 스크롤 스파이 활성 메뉴를 사용하고 있습니다. 헤더가 고정 된 위치이므로이 오프셋이 필요합니다.

윈도우가 900px 너비보다 작 으면 0px로 변경하려면 오프셋 값이 필요합니다. 그 시점에서 헤더 위치가 상대적이게되기 때문입니다.

$(document).ready(function() { 
$(window).scroll(function() { 

    var y = $(this).scrollTop(); 

    $('.link').each(function (event) { 
     if (y >= $($(this).attr('href')).offset().top - 100) { 
      $('.link').not(this).removeClass('active'); 
      $(this).addClass('active'); 
     } 
    }); 

}); 

});

$(function() { 
$('a[href*=#]:not([href=#])').click(function() { 
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); 
     if (target.length) { 
      $('html,body').animate({ 
       scrollTop: (target.offset().top - 100) 
      }, 850); 
      return false; 
     } 
    } 
}); 

});

+0

'$ (창) CSTE 연구진 ({...) 경우 ($ (창) .width <900}), 기능 ('크기 조정') ' – Blazemonger

+5

왜 이것에 대한 CSS 미디어 쿼리를 사용하지 ? 어쨌든 헤더가 CSS를 통해 고정되어 있다고 가정합니다. –

+0

@Blazemonger 빠른 답장을 보내 주셔서 감사합니다. 나는 당신의 제안을 시도했지만, 나는 그것을 올바르게하지 않을까 걱정됩니다. 내가 제공 한 코드와 관련하여 예제를 보여 주면서 친절하십니까? 고마워. –

답변

0

당신은 실제로 JS에서 미디어 쿼리와 비슷한 뭔가를 수행 만이 가진 작은 문제가 있습니다

if (matchMedia("(min-width: 900px)").matches) { 
    // the viewport is at least 900 pixels wide 
} 
+0

슬프게도 M $ 지원이 좋지 않습니다. IE 모바일에서는 아무 것도, 데스크톱에서는 IE10 이상이 아닙니다. https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia –

+1

[구식 브라우저에는 polyfill이 있습니다.] (https://github.com/paulirish/matchMedia.js/) – Blazemonger

1
function checkMatchMedia(pQuery) { 
    if (!window.matchMedia) {return false;} 
    if (window.matchMedia(pQuery).matches) {return true;} 
    return false; 
} 

var vIsOK = checkMatchMedia("(min-width: 500px)"); 
if (vIsOK) { 
    console.log('window width is at least 500px'); 
} else { 
    if (window.matchMedia) { 
     console.log('window width is less then 500px'); 
    } else { 
     console.log('Please include Polyfill.'); 
    } 
} 

, 그 이전의 IE는이를 지원하지 않는다는 것입니다.

polyfill이라는 라이브러리를 추가하여 수정되었습니다.

당신은 CSS에서 .resolution-check 클래스를 정의 할 수 있습니다
2

때 볼 수 있도록 : 단순히 JS에서 확인 후

@media only screen and (max-width: 900px) { 
    .resolution-check { 
    display: block; 
    } 
} 

및 그 요소가 표시되는 경우 :

if ($('.resolution-check').is(':visible')) { 

    // do stuff here 

} 

당신이 미디어 쿼리를 제어 할 수 있습니다이 방법 한 곳의 CSS에서

+0

나는 이것에서 DOM을 혼합하는 아이디어를 좋아하지 않는다 (적어도 마지막 옵션이있다!) – sv88erik

0

JavaScript에서 미디어 쿼리를 사용하고 div 또는 이미지 또는 텍스트를 바꾸는 방법 원어민 로고 변경 모바일

jQuery(function($){ 
     if (window.matchMedia("(max-width: 500px)").matches) { 
    $(".vc_responsive .logo > a > img ").replaceWith("<img class='img-responsive standard-logo' src='your URL' alt='Xtreme'>"); 
     } 
     }); 
관련 문제