检测滚动条是否可见(例如在移动设备上) [英] Detect if scrollbar is visible (e.g. on a mobile device)

查看:32
本文介绍了检测滚动条是否可见(例如在移动设备上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多关于检测 HTML 元素是否可滚动的问题/答案(例如 动态检测滚动条).我需要类似但不完全相同的东西.

I've seen lots of questions/answers regarding detecting if an HTML element is scrollable (e.g. Detect scrollbar dynamically ). I need something similar, but not quite the same.

我有一个 div 设置为 overflow-y: scroll;.在桌面浏览器上,它显示垂直滚动条;没关系.在 iPad 上,没有垂直滚动条;但你可以通过触摸滚动它.我遇到的问题是,在 iPad 上 视觉上并不总是可以滚动 div.Div 只包含一个列表;有时我的用户认为他们看到了整个列表,但如果他们滚动,则没有意识到还有更多.

I have a div set to overflow-y: scroll;. On a desktop browser it shows the vertical scrollbar; that's fine. On an iPad, there is no vertical scrollbar; but you can scroll it by touch. The problem I'm having is that it's not always visually obvious on an iPad that the div can be scrolled. The Div simply contains a list; and sometimes my users think they're seeing the entire list and don't realize there's more if they scroll.

我在想,如果我能以某种方式检测是否有可见滚动条——不仅仅是它是否可滚动——我可以为移动设备添加背景图像或类似的视觉提示没有滚动条的用户.但如果已经有滚动条,我不想要多余的提示.

I'm thinking that if I can somehow detect if there is a visible scrollbar -- not simply if it's scrollable or not -- I can add a background image or similar visual cue for the mobile users who don't have the scrollbar. But I don't want a redundant cue if there's already a scrollbar.

我愿意使用 JavaScript/PHP 解决方案来检测滚动条,或者使用其他方式(CSS?)来提示"一个部分可以滚动的事实.有什么想法吗?

I'm open either to JavaScript/PHP solutions to detect the scrollbar, or other ways (CSS?) to "cue" the fact that a section can be scrolled. Any ideas?

推荐答案

根据 Doug 关于比较 offsetWidths 的提示,这是我想出的可行解决方案.具有 vscroll 类的元素的样式为 overflow-y: scroll;.

Based on Doug's hint about comparing offsetWidths, here's a working solution I came up with. Elements with the vscroll class are styled overflow-y: scroll;.

$(document).ready(function () {
    var scrollables = document.getElementsByClassName('vscroll');
    if( scrollables.length && 0 === scrollables[0].offsetWidth - scrollables[0].clientWidth ) {
        for ( const scrollable of scrollables ) {
            scrollable.style.background = 'url("/images/updnarrows_75.png") no-repeat 60% 50%';
        }
    }
});

图像是一组在 div 背景中居中显示的淡化向上/向下箭头.

The image is a set of faded up/down arrows that appear centered in the background of the div.

这篇关于检测滚动条是否可见(例如在移动设备上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆