繁体   English   中英

如何检测滚动条是否存在?

[英]How do I detect whether a scrollbar exists?

我需要一些持续检测滚动条的代码。 如果找到滚动条,将额外的 50px 添加到 iframe 的高度,然后再次重新运行代码,最终将没有滚动条。 但是,我当前的代码不起作用。 我将如何在 HTML/CSS/JS 中执行此操作?

页面代码:

<script>
iframeheight()

function iframeheight() {
    alert('running');
var vs = window.innerWidth > document.documentElement.clientWidth;
    if vs > 0 {
    document.getElementById('maincode').style.height = currentheight + "50px";
    }
    else {}
    setTimeout(iframeheight, 1);
}
</script>

<iframe id="maincode" class="maincode" src="index2.html" frameBorder="0" border="0" 
onclick="iframeheight()"></iframe>

这是我的解决方案

关键是在document.documentElement上使用clientHeightscrollHeight
如果页面有滚动条, scrollHeight会比clientHeight

此外,我没有使用setTimeoutsetInterval (轮询),而是为resize事件创建了一个eventListener ,并在整个文档上创建了一个MutationObserver 这可能适合也可能不适合您的需求。 请注意,MutationObserver 可能会对性能产生重大影响,具体取决于具体情况。 有关详细信息,请参阅我的代码中的链接。

 "use strict"; { const hasScrollbar = (el) => { return el.scrollHeight > el.clientHeight } const checkScrollbar = () => { scrollbar = hasScrollbar(document.documentElement) viewUpdate() } let scrollbar; const viewUpdate = () => { if (scrollbar) { document.documentElement.style.backgroundColor = 'gold'; } else { document.documentElement.style.backgroundColor = 'silver'; } } window.addEventListener('resize', checkScrollbar) // be aware that MutationObserver may have performance issues // See https://stackoverflow.com/a/39332340/476951 const observer = new MutationObserver(checkScrollbar); const config = { attributes: true, childList: true, subtree: true }; observer.observe(document.documentElement, config); // For demonstration purpose const addContent = () => { document.body.appendChild(document.createElement('p')); } document.getElementById('btn-add').addEventListener('click', addContent) const removeContent = () => { document.body.removeChild(document.body.querySelector('p')); } document.getElementById('btn-remove').addEventListener('click', removeContent) }
 p { height: 100px; background-color: red; } p:nth-child(2n) { background-color: green; }
 <button id="btn-add">Add</button> <button id="btn-remove">Remove</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM