英文:
How can I set a javascript "if" conditional to activate based on mobile screen size?
问题
我有一个JavaScript代码,可以在滚动时使标题缩小。目前,我正在使用以下代码:
...
我想要修改代码,以便在移动设备上初始时标题就是缩小的。这样在窗口宽度小于768px时,就永远不会出现全尺寸的标题。
我尝试过添加以下代码,但并没有起作用:
...
任何帮助或指导将不胜感激。
提前致谢。
英文:
I have a javascript code which causes the header to scale on scroll. Currently, I am using this:
<script>
var y = window.scrollY
var hh = document.getElementById('header').offsetHeight
var shrinkHeader = function(){
console.log("y", window.scrollY)
if(window.scrollY === 0){
document.getElementById('header').style.height = '125px';
document.getElementById('content').style.paddingTop = '125px';
document.getElementById('header').classList.remove("small-image");
}else{
if(hh === 80){return;}else{
document.getElementById('header').style.height = '70px';
document.getElementById('content').style.paddingTop = '70px';
document.getElementById('header').classList.add("small-image");
}
}
}
window.onload = shrinkHeader;
window.onscroll = shrinkHeader;
</script>
I would like to modify so that the header initiates as shrunk on mobile. So that there is never a full size header when viewing on a window less than 768px.
I've tried adding this, however it did not work:
<script>
var y = window.scrollY
var hh = document.getElementById('header').offsetHeight
var shrinkHeader = function(){
console.log("y", window.scrollY)
if(window.scrollY === 0 && $(window).width() > 768){
document.getElementById('header').style.height = '125px';
document.getElementById('content').style.paddingTop = '125px';
document.getElementById('header').classList.remove("small-image");
}else{
if(hh === 80 || $(window).width() < 769){return;}else{
document.getElementById('header').style.height = '70px';
document.getElementById('content').style.paddingTop = '70px';
document.getElementById('header').classList.add("small-image");
}
}
}
window.onload = shrinkHeader;
window.onscroll = shrinkHeader;
</script>
Any help or redirection is appreciated.
Many thanks in advance.
答案1
得分: 1
使用Window:matchMedia()方法
示例:
if (window.matchMedia('(max-width: 768px)').matches) {
console.log('max-width: 767px');
} else {
console.log('min-width: 768px');
}
英文:
Use Window: matchMedia() method
Example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
if ( window.matchMedia('(max-width: 768px)').matches ) {
console.log('max-width: 767px');
} else {
console.log('min-width: 768px');
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论