是否有可能检查溢出:自动的一个div?

例如:

HTML

<div id="my_div" style="width: 100px; height:100px; overflow:auto;" class="my_class"> 
  * content
</div>

JQUERY

$('.my_class').live('hover', function (event)
{
    if (event.type == 'mouseenter')
    {
         if( ...  if scrollbar visible ? ... )
         {
            alert('true'):
         }
         else
         {
            alert('false'):
         }
    }

});

有时内容很短(没有滚动条),有时内容很长(滚动条可见)。


当前回答

也许有一个更简单的解决方案。

if ($(document).height() > $(window).height()) {
    // scrollbar
}

其他回答

我为jQuery做了一个新的自定义:pseudo选择器来测试一个项目是否具有以下css属性之一:

溢出(滚动|汽车): overflow-x(滚动|汽车): overflow-y(滚动|汽车):

我想找到另一个元素的最近的可滚动父元素,所以我还写了另一个小jQuery插件来找到最近的溢出父元素。

这种解决方案可能不是最好的,但它似乎确实有效。我将它与$。scrollTo插件。有时我需要知道一个元素是否在另一个可滚动容器中。在这种情况下,我想滚动父滚动元素与窗口。

我可能应该把它包装在一个单独的插件中,并添加psuedo选择器作为插件的一部分,以及公开一个“最近”方法来查找最近的(父)可滚动容器。

Anywho……在这儿。

美元。isScrollable jQuery插件:

$.fn.isScrollable = function(){
    var elem = $(this);
    return (
    elem.css('overflow') == 'scroll'
        || elem.css('overflow') == 'auto'
        || elem.css('overflow-x') == 'scroll'
        || elem.css('overflow-x') == 'auto'
        || elem.css('overflow-y') == 'scroll'
        || elem.css('overflow-y') == 'auto'
    );
};

$(':scrollable') jQuery伪选择器:

$.expr[":"].scrollable = function(a) {
    var elem = $(a);
    return elem.isScrollable();
};

jQuery插件$.scrollableparent()

$.fn.scrollableparent = function(){
    return $(this).closest(':scrollable') || $(window); //default to $('html') instead?
};

实现非常简单

//does a specific element have overflow scroll?
var somedivIsScrollable = $(this).isScrollable();
//use :scrollable psuedo selector to find a collection of child scrollable elements
var scrollableChildren = $(this).find(':scrollable');
//use $.scrollableparent to find closest scrollable container
var scrollableparent = $(this).scrollableparent();

更新:我发现Robert Koritnik已经提出了一个更强大的:可滚动的伪选择器,它将识别可滚动容器的可滚动轴和高度,作为他的$.scrollintoview() jQuery插件的一部分。scrollintoview插件

下面是他的花哨的伪选择器(道具):

    $.extend($.expr[":"], {

    scrollable: function (element, index, meta, stack) {

        var direction = converter[typeof (meta[3]) === "string" && meta[3].toLowerCase()] || converter.both;

        var styles = (document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(element, null) : element.currentStyle);

        var overflow = {

            x: scrollValue[styles.overflowX.toLowerCase()] || false,

            y: scrollValue[styles.overflowY.toLowerCase()] || false,

            isRoot: rootrx.test(element.nodeName)

        };



        // check if completely unscrollable (exclude HTML element because it's special)

        if (!overflow.x && !overflow.y && !overflow.isRoot)

        {

            return false;

        }



        var size = {

            height: {

                scroll: element.scrollHeight,

                client: element.clientHeight

            },

            width: {

                scroll: element.scrollWidth,

                client: element.clientWidth

            },

            // check overflow.x/y because iPad (and possibly other tablets) don't dislay scrollbars

            scrollableX: function () {

                return (overflow.x || overflow.isRoot) && this.width.scroll > this.width.client;

            },

            scrollableY: function () {

                return (overflow.y || overflow.isRoot) && this.height.scroll > this.height.client;

            }

        };

        return direction.y && size.scrollableY() || direction.x && size.scrollableX();

    }

});

这是我的改进:添加parseInt。出于某种奇怪的原因,没有它就不能工作。

// usage: jQuery('#my_div1').hasVerticalScrollBar();
// Credit: http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible
(function($) {
    $.fn.hasVerticalScrollBar = function() {
        return this.get(0) ? parseInt( this.get(0).scrollHeight ) > parseInt( this.innerHeight() ) : false;
    };
})(jQuery);

至少在新版本的Chrome、Edge、Firefox和Opera上都可以使用。

使用JQuery……

设置这个函数来修复页脚:

function fixFooterCaller()
{
    const body = $('body');
    const footer = $('body footer');

    return function ()
    {
        // If the scroll bar is visible
        if ($(document).height() > $(window).height())
        {
            // Reset
            footer.css('position', 'inherit');
            // Erase the padding added in the above code
            body.css('padding-bottom', '0');
        }
        // If the scrollbar is NOT visible
        else
        {
            // Make it fixed at the bottom
            footer.css('position', 'fixed');
            // And put a padding to the body as the size of the footer
            // This makes the footer do not cover the content and when
            // it does, this event fix it
            body.css('padding-bottom', footer.outerHeight());
        }
    }
}

它返回一个函数。这样做只是为了设置一次正文和页脚。

然后,在文档准备好时设置这个。

$(document).ready(function ()
{
    const fixFooter = fixFooterCaller();

    // Put in a timeout call instead of just call the fixFooter function
    // to prevent the page elements needed don't be ready at this time
    setTimeout(fixFooter, 0);
    // The function must be called every time the window is resized
    $(window).resize(fixFooter);
});

添加这个到你的页脚css:

footer {
    bottom: 0;
}

您可以使用Element的组合来做到这一点。scrollHeight和Element。clientHeight属性。

根据MDN:

元素。scrollHeight只读属性是对元素内容高度的测量,包括由于溢出而在屏幕上不可见的内容。scrollHeight值等于元素为了适应视点中的所有内容而不使用垂直滚动条所需的最小clientHeight。它包括元素的填充,但不包括它的边距。

And:

元素。clientHeight只读属性返回元素的内部高度(以像素为单位),包括填充,但不包括水平滚动条高度、边框或边距。 clientHeight可以计算为CSS高度+ CSS填充-水平滚动条的高度(如果存在的话)。

因此,如果滚动高度大于客户端高度,元素将显示滚动条,所以你的问题的答案是:

function scrollbarVisible(element) {
  return element.scrollHeight > element.clientHeight;
}

对于那些像我一样使用现代js框架而不是JQuery的可怜人,我将进一步扩展这一点,并被这个线程的人完全抛弃:

这是用Angular 6写的,但如果你写React 16、Vue 2、Polymer、Ionic、React- native,你就知道怎么去适应它了。这是整个组件,所以应该很简单。

import {ElementRef, AfterViewInit} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.html',
  styleUrls: ['./app.scss']
})
export class App implements AfterViewInit {
scrollAmount;

constructor(
  private fb: FormBuilder,
  private element: ElementRef 
) {}

ngAfterViewInit(){
  this.scrollAmount = this.element.nativeElement.querySelector('.elem-list');
  this.scrollAmount.addEventListener('wheel', e => { //you can put () instead of e
  // but e is usefull if you require the deltaY amount.
    if(this.scrollAmount.scrollHeight > this.scrollAmount.offsetHeight){
       // there is a scroll bar, do something!
    }else{
       // there is NO scroll bar, do something!
    }
  });
}
}

在HTML中会有一个带有类“element -list”的div,它在CSS或SCSS中被风格化,具有不隐藏的高度和溢出值。(自动或滚动)

我在滚动事件时触发这个eval,因为我的最终目标是拥有“自动焦点滚动”,它决定是否在所述组件没有垂直滚动可用时水平滚动整个组件集,否则只垂直滚动其中一个组件的内部。

但是你可以把eval放在其他地方,让它被其他东西触发。

这里需要记住的重要一点是,你永远不会被迫重新使用JQuery,总有一种方法可以在不使用它的情况下访问它的相同功能。