[英]Using JavaScript to delete div in screen size below a certain pixel
我是編碼的新手。 我知道這可以通過css完成,但是想通過使用JavaScript來實現。 我有一個div標簽,並希望不在630px屏幕尺寸下顯示它。 我搜索了這個網站並在另一個問題中找到了這個JavaScript代碼,我喜歡它:
if( window.innerWidth > 630 ) {
//Your Code
}
但是,由於我是新手,我不熟悉如何在我的PHP代碼中插入它以及在哪里插入div所以它只適用於630px以上的屏幕。
這是一種在屏幕寬度小於700px時隱藏div的方法
function myFunction(x) { if (x.matches) { // If media query matches document.getElementById("divIWantedToHide").style.visibility = "hidden"; } else { document.getElementById("divIWantedToHide").style.visibility = "visible"; } } var x = window.matchMedia("(max-width: 700px)") myFunction(x) // Call listener function at run time x.addListener(myFunction)
<div id="divIWantedToHide"> tset </div>
就個人而言,我建議你使用CSS來獲得更精確的媒體查詢。
@media only screen and (max-width: 700px) { #divIWantedToHide { display: none; } }
<div id="divIWantedToHide"> tset </div>
這更像是一個event
問題:
在基本級別,這是您可以通過resize
event
切換的方式:
var el = document.getElementById("yes"); //get the element node //target resize event window.onresize = function(){ //this will check everytime a resize happens if(window.innerWidth > 630) { //if width is still bigger than 630, keep the element visible el.style.display = "block"; //exit the funtion return; } //At this point, the width is less than or equals to 630, so hide the element el.style.display = "none"; }
<div id="yes"> Yey! I am visible </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.