制作网站页面时,经常会遇到调整页面的各种需求,其中,基于各种原因隐藏页面中的滚动条,就是一种常见需求,那么,网站页面中到底可以不可以隐藏滚动条?该如何编写代码设置隐藏页面中的滚动条?接下来,济南网站建设小编就来为大家分享,通过编写JavaScript代码来实现页面隐藏滚动条的一个小案例,希望可以对有需要的朋友有所帮助。
关键代码:
<head>
<title>JavaScript隐藏页面滚动条</title>
<style>
body {
/* 让页面产生滚动区域 */
height: 2000px;
margin: 0;
padding: 20px;
background: #f5f5f5;
}
/* 兼容 Chrome、Edge、新版浏览器 */
::-webkit-scrollbar {
display: none;
}
/* 兼容 IE */
body {
-ms-overflow-style: none;
}
/* 兼容 Firefox */
html {
scrollbar-width: none;
}
</style>
</head>
<body>
<h3>页面滚动条已隐藏</h3>
<p>鼠标滚轮、键盘方向键依旧可以滚动页面,只是看不到滚动条</p>
<script>
// 附加简单JS示例:点击按钮切换滚动条显示/隐藏
const btn = document.createElement('button');
btn.innerText = '切换滚动条状态';
btn.style.padding = '8px 16px';
btn.style.margin = '20px 0';
document.body.prepend(btn);
let isHide = true;
btn.onclick = function() {
const style = document.createElement('style');
if (isHide) {
// 恢复滚动条
document.querySelectorAll('style').forEach(item => {
if(item.textContent.includes('scrollbar')) item.remove();
});
isHide = false;
} else {
// 重新隐藏滚动条
style.textContent = `
::-webkit-scrollbar{display:none;}
body{-ms-overflow-style:none;}
html{scrollbar-width:none;}
`;
document.head.appendChild(style);
isHide = true;
}
}
</script>
</body>
评论