簡體   English   中英

jQuery無法與CSS媒體查詢一起使用

[英]jquery not working with css media queries

我有一個名為“ .left”的元素。 它的CSS看起來像這樣:

.left{
  float:right;
  background-repeat: no-repeat;
  width: 300px;
  height: 100%;}

我對此元素有一個媒體查詢,如下所示:

@media screen and (max-width: 570px) {
    .left{
      display: none;}
 }

我想做的是激活媒體查詢后,有一個名為“ .close”的按鈕來更改其功能。 如果要顯示,我希望一,二,三淡入:如果顯示不= none,則一,二,三,四要淡入淡出。 這是我到目前為止在jQuery中的內容:

<script>
    $( document ).ready(function($) {
        console.log( "ready!" );

        $(".close").on('click',function() {
            if ($(".left").css("display") == "none" ){
                $("#one,#two,#three").fadeIn();}
            else {
                $("#one,#two,#three,#four").fadeIn();}
        });
    });
</script>

但是,無論瀏覽器的大小如何,我編寫的代碼僅執行if條件,而不執行else條件。

我需要協助! 謝謝!

嘗試

:隱藏選擇器

.is()

$(document).ready(function ($) {
    console.log("ready!");
    $(".close").on('click', function () {
        if ($(".left").is(":hidden")) { //check if .left is hidden or not
            $("#one,#two,#three").fadeIn();
        } else {
            $("#one,#two,#three,#four").fadeIn();
        }
    });
});

您應該在javascript中使用媒體查詢。 看這里:

https://developer.mozilla.org/zh-CN/docs/Web/API/Window.matchMedia

$( document ).ready(function($) {
    console.log( "ready!" );

    $(".close").on('click',function() {

      if(window.matchMedia("(max-width: 570px)").matches) {
        $("#one,#two,#three").fadeIn();}
      } else {
        $("#one,#two,#three,#four").fadeIn();}
      }

    });
});

暫無
暫無

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

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