简体   繁体   English

使用JavaScript删除屏幕大小低于某个像素的div

[英]Using JavaScript to delete div in screen size below a certain pixel

I'm a newbie in coding. 我是编码的新手。 I knew this can be done by css, but want to do it by using JavaScript. 我知道这可以通过css完成,但是想通过使用JavaScript来实现。 I have a div tag and would like to not show it under 630px screen size. 我有一个div标签,并希望不在630px屏幕尺寸下显示它。 I searched this site and find this JavaScript code in another question and I liked it: 我搜索了这个网站并在另一个问题中找到了这个JavaScript代码,我喜欢它:

if( window.innerWidth > 630 ) {
//Your Code
}

But as I'm newbie I'm not familiar on how to insert it in my PHP code and where to insert div so it only works for screen above 630px. 但是,由于我是新手,我不熟悉如何在我的PHP代码中插入它以及在哪里插入div所以它只适用于630px以上的屏幕。

Here is a way to hide a div when the width of the screen is smaller then 700px 这是一种在屏幕宽度小于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> 

Fiddle 小提琴

Personally I would recommend you to use CSS for this to be more precise media querys. 就个人而言,我建议你使用CSS来获得更精确的媒体查询。

 @media only screen and (max-width: 700px) { #divIWantedToHide { display: none; } } 
 <div id="divIWantedToHide"> tset </div> 

Fiddle 小提琴

This is more of an event issue: 这更像是一个event问题:

At the basic level, this is how you could toggle by resize 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM