在正文中使用css:
.noScroll { overflow: hidden !important; }
JS公司:
document.body.classList.add('noScoll')
document.body.classList.remove('noScoll')
[编辑]回应
The Old County
下面是要添加的代码部分,以便页面在有或没有滚动条的情况下保持在同一位置:
const Remove_ScrollBars =_=>
{
let xLeft = document.body.scrollLeft
, yTop = document.body.scrollTop
document.body.classList.add('noScroll')
document.body.scrollLeft = xLeft
document.body.scrollTop = yTop
}
const Return_ScrollBars =_=>
{
let xLeft = document.body.scrollLeft
, yTop = document.body.scrollTop
document.body.classList.remove('noScroll')
document.body.scrollLeft = xLeft
document.body.scrollTop = yTop
}
演示1:
const Remove_ScrollBars =_=>
{
let xLeft = document.body.scrollLeft
, yTop = document.body.scrollTop
document.body.classList.add('noScroll')
document.body.scrollLeft = xLeft
document.body.scrollTop = yTop
}
const Return_ScrollBars =_=>
{
let xLeft = document.body.scrollLeft
, yTop = document.body.scrollTop
document.body.classList.remove('noScroll')
document.body.scrollLeft = xLeft
document.body.scrollTop = yTop
}
noScrollBar.onclick = Remove_ScrollBars
ScrollBar.onclick = Return_ScrollBars
.noScroll {
overflow: hidden !important;
}
p { white-space: nowrap; }
<p>aa</p>
<p>bb</p>
<p>cc</p>
<p>dd</p>
<p>cc</p>
<p>dd</p>
<p>aa</p>
<p>bb</p>
<p>cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc </p>
<p>dd</p>
<p>aa</p>
<p>aa</p>
<p>_ _ _ _ _ _ _ _ _ _ <button id="noScrollBar">Scroll Bar Off </button> </p>
<p>_ _ _ _ _ _ _ _ _ _ <button id="ScrollBar"> Scroll Bar On </button> </p>
<p>bb</p>
<p>cc</p>
[编辑:2]
好吧,正如你坚持的那样,我看了你要找的答案的类型多一点(保持滚动条,但使其不活动)
所以这里有一个新的方法,我希望有什么好处?
var WindowPos = { x:window.scrollX, y:window.scrollY, fix : false }
const FixScroll = bool => WindowPos.fix = bool
window.onscroll =_=>{
if (WindowPos.fix) window.scrollTo(WindowPos.x, WindowPos.y)
else {
WindowPos.x = window.scrollX
WindowPos.y = window.scrollY
}
}
演示2:
var WindowPos = { x:window.scrollX, y:window.scrollY, fix : false }
const FixScroll = bool => WindowPos.fix = bool
window.onscroll =_=>{
if (WindowPos.fix) window.scrollTo(WindowPos.x, WindowPos.y)
else {
WindowPos.x = window.scrollX
WindowPos.y = window.scrollY
}
}
fixBars.onclick =_=>{
fixBars.innerText = FixScroll( !WindowPos.fix ) ? 'Set Scroll Bar On' : 'Set Scroll Bar Off'
}
p { white-space: nowrap; }
<p>aa</p>
<p>bb</p>
<p>cc</p>
<p>dd</p>
<p>cc</p>
<p>dd</p>
<p>aa</p>
<p>aa</p>
<p>dd</p>
<p>dd</p>
<p>aa</p>
<p>aa</p>
<p>dd</p>
<p>aa</p>
<p>bb</p>
<p>cc</p>
<p>dd</p>
<p>cc</p>
<p>dd</p>
<p>aa</p>
<p>bb</p>
<p>cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc </p>
<p>dd</p>
<p>_ _ _ _ _ _ _ _ _ _ <button id="fixBars">Set Scroll Bar Off</button> </p>
<p>bb</p>
<p>cc</p>
<p>dd</p>
<p>dd</p>
<p>dd</p>
<p>aa</p>
<p>aa</p>
<p>dd</p>
<p>aa</p>
<p>bb</p>
<p>cc</p>
<p>dd</p>
<p>cc</p>
<p>dd</p>