簡體   English   中英

我需要一些JavaScript條件,例如媒體查詢

[英]I need some javascript condition like media query

我想在jquery中添加一些條件,例如CSS中的媒體查詢,有人可以幫助我嗎? 我嘗試下面的代碼,但無法正常工作:

   jQuery(document).ready(function(){
        if (jQuery(window).width() >= 320) && (jQuery(window).width() <= 479) {

        }  

        if (jQuery(window).width() >= 480) && (jQuery(window).width() <= 567) {

        }  
    });

您在各個條件周圍都有括號,但在整個if條件周圍沒有括號。

嘗試這個:

jQuery(document).ready(function(){
        alert("Running");
        alert(jQuery(window).width());
        if ((jQuery(window).width() >= 320) && (jQuery(window).width() <= 479)) {
            alert('Small screen');
        } else

        if ((jQuery(window).width() >= 480) && (jQuery(window).width() <= 567)) {
            alert('Large screen');
        }  else {
            alert("Biggest screen");
        }
});

注意額外的括號后if之前{

實際上,您不需要JS中的媒體查詢即可以正確的方式完成任務。 首先:如何在JS中處理媒體查詢。 您可以使用matchMedia 這是一個簡短的文檔

這是一個簡單的示例:

var smallMatcher = matchMedia('(max-width: 480px)');
var biggerMatcher = matchMedia('(max-width: 1024px)');

var run = function(){
    if(smallMatcher.matches) {
        //run code for small
    } else if(biggerMatcher.matches){
        //run code for bigger
    } else {
        //run code for else
    }
};

//now run it
run();

//in case you need to dynamically change on resize
//use addListener
smallMatcher.addListener(run);
biggerMatcher.addListener(run);

但是正如您所說,您不需要此。 您實際需要做的是簡單地將關注點分離。 不要將您的行為與CSS混在一起。 只需添加focus / blur或focusin / focusout事件,添加或刪除類,然后在CSS中進行其他所有操作即可。

這應該產生干凈和簡單的代碼,這是一個示例

$('#searchbox')
    .on('focus', function(){
        $(this).closest('form').addClass('focused-field');
    })
    .on('blur', function(){
        $(this).closest('form').removeClass('focused-field');
    })
;

其他所有內容都可以並且應該在CSS中處理。

並且如果您需要修改輸入按鈕的樣式,如果按鈕本身是聚焦的,不僅是搜索輸入,您還會看到下面的小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM