2017-02-23 62 views
-3

我想從特定元素中移除一個類,並使用JS根據窗口寬度添加另一個類。我寫了下面的代碼,但它不會工作。嘗試爲每個元素移除/添加類

jQuery(function($) { 
      var facebook = (".fa-facebook-square"); 
      var twitter = (".fa-twitter-square"); 
      var social = [facebook, twitter]; 
      if ($(window).width() < 768) { 
       for (var i = 0; i < social.length; i++) { 
        var $socialCon = "$" + "('" + i + "')"; 
        $socialCon.removeClass('fa-5x'); 
        $socialCon.addClass('fa-4x'); 
       } 
       } 
     }); 
+1

有什麼用意?你可以用純CSS通過媒體查詢實現你想要的任何樣式:'@media only screen and(min-width:768px)' –

回答

1

您應該先嚐試瞭解JavaScript和jQuery的工作原理。互聯網上有很多很棒的網站。

$(function() { 
    if ($(window).width() < 768) { 
    $(".fa-facebook-square, .fa-twitter-square") 
     .removeClass('fa-5x') 
     .addClass('fa-4x'); 
    } 
}); 
+0

謝謝你的結構。我現在正在學習,所以我希望在不久的將來我不會問這樣的問題。 順便說一句,當我將'(window.width <768)'改爲'$(window).width()' –

+0

後,我的代碼就開始爲我工作了。我並不是想要聽起來不禮貌,重新嘗試去做需要對這個話題有一定的瞭解。也許你是前進的一步。 – sjngm

+0

@VasylKozhushko我編輯了我的答案。 – sjngm

0

使用JavaScript處理元素類的Instaid最好是使用媒體查詢簡單地添加CSS規則。更多信息here

#msg { 
 
    background-color: yellow; 
 
} 
 
@media screen and (min-width: 768px) { 
 
    #msg { 
 
    background-color: green; 
 
    } 
 
}
<span id="msg">Green background if screen is at least 768px in width, yellow if not.</span>

0

如果你想添加的風格,那麼我會建議使用一個媒體查詢,您可以針對該類fa-4x與選擇的強鏈,如果需要的話。 How CSS selectors work:

您可以使用像這樣:

.fa-5x { 
    background-color: #000000; 
    padding: 40px; 
} 

@media only screen and (max-width: 767px) { 
    .fa-twitter-square.fa-4x { 
     background-color: #ff0000; 
     padding: 0 20px 0; 
    } 
} 

如果你真的想使用JS,那麼你可以做這樣的事情上面:

$(function() { 
    var width = window.innerWidth; 
    if (width < 768) { 
     $(".fa-facebook-square, .fa-twitter-square") 
      .removeClass('fa-5x') 
      .addClass('fa-4x'); 
    } 
}); 

如果你需要留意的情況下調整你需要一個響應網站,你需要等待任何調整大小事件,然後調用一個函數來做你想做的事情。

var over767px = function() { 
    var windowWidth = window.innerWidth; 
    if (windowWidth > 767) { 
     //perform tablet/desktop code here 
    } else if (windowWidth < 768) { 
     //perform mobile code here 
    } 
}; 

var debouncer = function(func , timeout) { 
    var timeoutID , timeout = timeout || 50; 
    return function() { 
     var scope = this , args = arguments; 
     clearTimeout(timeoutID); 
     timeoutID = setTimeout(function() { 
      func.apply(scope , Array.prototype.slice.call(args)); 
     } , timeout); 
    }; 
}; 

$(window).resize(debouncer(function (e) { 
    over767px(); 
})); 
相關問題