仅使用jquery或css在小屏幕上显示div

时间:2017-09-02 10:56:27

标签: javascript jquery html css

我想在小屏幕上显示这个HTML代码。

<div id="NightDiv" class="w3-center" style="padding-top:20px"><i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon"  aria-hidden="true"></i>
</div>

这是我正在尝试但没有成功:

$(document).ready(function() {

if ((screen.width>=1024) ) {
 $("#NightDiv").hide();
}
else {
 $("#NightDiv").show();

}
});

5 个答案:

答案 0 :(得分:6)

您不需要JavaScript。使用CSS Media Query执行此操作,

/*Hide for larger screens*/
#NightDiv {
   display: none;
}

/*show for small screens */
@media screen and (max-width: 1023px) { /* I've given 1023px but you can change to proper width */
    #NightDiv {
        display: block;
    }
}

答案 1 :(得分:1)

CSS媒体查询可以更好地处理这个问题。请参阅下面的示例:(展开代码段以隐藏div)

//no javascript!
.w3-center {
  display: none; /* hide by default */
}

@media(max-width:1024px){
  .w3-center {
    display: block; /* or inline, or whichever style you prefer*/
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<div id="NightDiv" class="w3-center" style="padding-top:20px"><i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon"  aria-hidden="true"></i>
</div>

答案 2 :(得分:1)

<div id="NightDiv" class="w3-center" style="padding-top:20px">
    <i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon"  aria-hidden="true"></i>
</div>

<style>
    #NightDiv{
        display: none;
    }
    @media only screen and (max-width:768px{
        #NightDiv{
            display: block;
        }
    }
</style>

答案 3 :(得分:0)

ShowDiv();
$(window).resize(function() {
  ShowDiv();
});

function ShowDiv(){
      if (window.innerWidth>=1024 )
         $("#NightDiv").hide();
      else 
        $("#NightDiv").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div  id="NightDiv" class="w3-center" style="padding-top:20px;width:200px;height:100px;background-color:pink;"><i id="nightMode2" class="fa fa-moon-o fa-lightbulb-o w3-cursor-pointer w3-amazon"  aria-hidden="true"></i>
</div>

答案 4 :(得分:0)

试试此代码

 jQuery(document).ready(function () {
        jQuery('#NightDiv').hide();
        // Display the div on mobile resoultions
        if (jQuery(window).width() < 700) {
            jQuery('#NightDiv').show();
        }
    });