我是编码新手。我知道这可以通过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>