2017-02-21 64 views
0

我在我的網站上使用視差效果,但是當屏幕較小時,背景圖像開始被切斷一點。我決定只在桌面上產生視差效果,並將其從其他較小的設備上移除。JS:刪除課程

比如我有3個部分

<section class="bg1 parallax"></section> 
<section class="bg2 parallax"></section> 
<section class="bg3 parallax"></section> 

視差類沒有在CSS中所描述的,它被添加只是爲了讓JavaScript的知道哪些部分視差應包括。

我的問題

已經有人得到了一個腳本,可以刪除類「視差」,如果屏幕寬度小於例如小:1280px?

如果寬度大於1280px

<section class="bg1 parallax"></section> 

否則

<section class="bg1"></section> 
+0

歡迎來到Stack Overflow!請閱讀[問]。重要短語:「搜索和研究」和「解釋......阻止你自己解決它的任何困難」。例如,http://stackoverflow.com/questions/2155737/remove-css-class-from-element-with-javascript-no-jquery?rq=1告訴你如何去除一個類,然後http:// stackoverflow .com/q/15840347/215552告訴你如何獲得屏幕的寬度。 –

回答

0

我沒有測試過,但是這個應該把你在正確的方向...

window.onresize = function(){ // may not be the window object 
    if (screen.width < 1280) { // many ways of detecting screen width 
     var sections = document.querySelectorAll("section"); // create array of all section elements 
     for (var i = 0; i <= sections.length-1; i++) { // loop through them 
      sections[i].classList.remove("parallax"); // remove their parallax class 
     }; 
    }; 
}; 
0

它看到毫秒有點哈克,但你可以做這樣的事情:

// closure so we don't pollute global scope. This should be run at the bottom of the page so that it can find all of the parallax elements on the page 
(function(){ 
    var previous_width = 0; 
    var cutoff = 1280; 
    var $parallax_elements = $('.parallax'); 
    function check_width() { 
     var current_width = document.body.clientWidth; 
     // if the document has gone from narrow to wide, re-enable parallax 
     if (current_width > cutoff && previous_width <= cutoff) { 
      $parallax_elements.addClass('parallax'); 
     } 
     // if the document has gone from wide to narrow, disable parallax 
     else if (current_width <= cutoff && previous_width > cutoff) { 
      $parallax_elements.removeClass('parallax'); 
     } 
     // store the current width for the next check 
     previous_width = current_width; 
    } 

    // run it every time the window resizes 
    $(window).resize(check_width); 

    // run it once to initialize 
    check_width(); 
})(); 
+0

在他的問題中沒有提到jQuery。 – Slime

0

試過這在控制檯,似乎工作。

if(window.innerWidth < 1280){ 
    var parallaxes = document.getElementsByClassName('parallax'); 
    while(parallaxes[0]){ 
     parallaxes[0].classList.remove('parallax'); 
    } 
}