[英]Show a div only on small screens with jquery or 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();
}
});
您不需要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;
}
}
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>
<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>
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>
試試這個代碼
jQuery(document).ready(function () {
jQuery('#NightDiv').hide();
// Display the div on mobile resoultions
if (jQuery(window).width() < 700) {
jQuery('#NightDiv').show();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.