簡體   English   中英

如何使用JQUERY生成媒體查詢

[英]how to generate media queries with JQUERY

當用戶使用小於桌面的設備訪問頁面時,我試圖顯示一個對話框。 我不是jQuery專家。 我在下面嘗試了以下方法,但未成功。

$(document).ready(function () {
  if (window.matchMedia('(max-width: 767px)').matches) {
    var dialog = $("#ScreenSize").dialog({
      modal: true,
      autoopen: true,
    }).show();
  } else {
    $("ScreenSize").dialog().hide();
  }
});
<div id="ScreenSize" style="display:none">
  <p>Go to Text Box</p>
</div>

此代碼在Dom准備就緒時執行。 考慮到您僅在if分支中打開該對話框,實際上else分支是無用的,因為當您重新加載頁面時,根本不會打開它。 也許您沒有提供其他邏輯。

然后.dialog()是jQuery UI庫的一種方法。 您還應該添加該庫,以使對話框正常工作。 如果打開控制台,則會看到方法dialog()未定義。

您的JavaScript代碼正常。 在html部分,必須以正確的順序加載jQuery和jQuery UI(用於對話框小部件)腳本:首先是jQuery,然后是UI。 嘗試以下代碼片段,它可以根據需要運行。

 $(document).ready(function () { if (window.matchMedia('(max-width: 767px)').matches) { var dialog = $("#ScreenSize").dialog({ modal: true, autoopen: true }).show(); } else { // this part is useless... $("ScreenSize").dialog().hide(); } }); 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" /> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div id="ScreenSize" style="display:none"> <p>Go to Text Box</p> </div> </body> </html> 

為什么需要jQuery? 為什么不只使用CSS媒體查詢來顯示和隱藏對話框。

CSS:

#ScreenSize {
  display: none;
}

@media only screen and (max-width: 767px) {
    #ScreenSize {
        display: block;
    }
}

我在下面使用以下這些命令來找到解決我的問題的方法

    $(function () {
    if (screen.width < 1023) {
        $("#ScreenSize").show();


        var dialog = $("#ScreenSize").dialog({

            modal: true,
            autoopen: true,
            resizable: false, draggable: false,



        })


    }
    else {
        $("#ScreenSize").hide();
    }


});

<span class="ui-state-default ui-corner-all" style="float: left; margin: 0 7px 0 0;"><span class="ui-icon ui-icon-info" style="float: left;"></span></span>

    <div style="margin-left: 23px;">


     <p>go to Text Box</p>
 </div>
                     <//div>

暫無
暫無

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

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