javascript - 当屏幕尺寸大于 700 像素时,如何使用 javascript 只让我的标题菜单缩小?
问题描述
下面是我的网站: KaiNanfelt_Music
我试图让我的标题(菜单)在滚动时缩小,整个代码看起来像这样:
所以它适用于所有屏幕,但我希望它仅在屏幕尺寸大于 700px 时才有效,我应该如何处理它和任何建议?谢谢!
// When the user scrolls down 80px from the top of the document, resize the navbar's padding and the logo's font size
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
document.getElementById("menu").style.padding = "0px";
document.getElementById("menu").style.margin = "0px 0px 0px 10px";
document.getElementById("site-title").style.fontSize = "3.5em";
document.getElementById("site-title").style.float = "left";
document.getElementById("site-title").style.margin = "20px 0 10px 0";
document.getElementsByClassName("menu").style.float = "right";
} else {
document.getElementById("menu").style.padding = "10px";
document.getElementById("site-title").style.fontSize = "6.8em";
document.getElementById("site-title").style.float = "none";
}
}
#menu {
transition: 0.5s;
position: fixed;
width: 100%;
top: 0;
z-index: 200;
overflow: hidden;
background: #ffffff;
;
}
<nav id="menu">
<button class="nav-button">Toggle Navigation</button>
<div id="site-title">
<a href="#" title="home" rel="home">
Home
</a>
</div>
</nav>
解决方案
在条件语句中使用带有 clientWidth 的 documentElement 来查看屏幕宽度是否大于 700,如果是,请运行您的函数...
注意:我在示例中使用了 600 像素,因为片段中的视口低于 700
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
console.log('current viewport: ' + viewportWidth)
window.onscroll = function() {
if (viewportWidth > 600) {
//<-- console.log just to illustrate that the sizing works, resize your screen and test
console.log(' Window is larger than 600 px');
// run your scrollFunction()
}
};
<!--Force a scroll using break tags for testing--><br>
'view in full screen'<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
推荐阅读
- javascript - 如何使用 d3.js 绘制螺旋气泡图
- c++ - 为什么我不能直接将字符串文字作为非类型模板参数传递?
- python - 从 %-style 格式字符串模板中提取键
- python - 如何修复 PyGame 中闪烁的绘图?只更新一次屏幕
- google-secret-manager - 获取最新版本的应用引擎云密文的好方法是什么?
- attributes - 为什么会出现此属性错误,解决方法是什么
- c# - ML.NET 如何检测 C# 中方法链的结尾?
- java - Elasticsearch Java:无法为对象堆错误保留足够的空间
- typescript - 当与字符串原始类型联合时,使打字稿显示字符串文字的类型提示
- python - 检查列表中是否只有一种元素是连续的?