[jquery] 스크롤바가 보이는지 어떻게 확인할 수 있습니까?

overflow:auto사업부의 확인이 가능 합니까?

예를 들면 다음과 같습니다.

HTML

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

쿼리

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

});

때때로 내용이 짧거나 (스크롤바 없음) 때로는 길다 (스크롤바가 표시됨).



답변

작은 플러그인.

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);

이렇게 사용하세요

$('#my_div1').hasScrollBar(); // returns true if there's a `vertical` scrollbar, false otherwise..

Firefox, Chrome, IE6,7,8에서 작동 테스트

그러나 제대로 작동하지 않습니다 body태그 선택기

데모


편집하다

세로 스크롤 막대가 나타나는 가로 스크롤 막대가 있으면이 기능이 작동하지 않는다는 것을 알았습니다.

다른 해결책을 찾았습니다 … 사용 clientHeight

return this.get(0).scrollHeight > this.get(0).clientHeight;


답변

아마도 더 간단한 해결책 일 것입니다.

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


답변

Element.scrollHeightElement.clientHeight속성을 조합하여이 작업을 수행 할 수 있습니다 .

MDN에 따르면 :

Element.scrollHeight는 읽기 전용 특성 때문에 오버플 화면에 보이지 않는 내용을 포함하는 요소의 내용의 높이를 측정한다. scrollHeight 값은 세로 스크롤 막대를 사용하지 않고 뷰의 모든 내용을 맞추기 위해 요소에 필요한 최소 clientHeight와 같습니다. 요소 패딩은 포함하지만 여백은 포함하지 않습니다.

과:

Element.clientHeight 읽기 전용 속성을 반환에게 요소의 내부 높이를 패딩 아니라 수평 스크롤 바의 높이, 테두리, 또는 여백을 포함하여 픽셀에.

clientHeight는 CSS 높이 + CSS 패딩-가로 스크롤 막대의 높이 (있는 경우)로 계산할 수 있습니다.

따라서 스크롤 높이가 클라이언트 높이보다 큰 경우 요소에 스크롤 막대가 표시되므로 질문에 대한 답변은 다음과 같습니다.

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


답변

나는 Reigel의 말을 약간 바꿔야합니다.

(function($) {
    $.fn.hasScrollBar = function() {
        return this[0] ? this[0].scrollHeight > this.innerHeight() : false;
    }
})(jQuery);

innerHeight는 컨트롤의 높이와 상단 및 하단 패딩을 계산합니다.


답변

이것은 @Reigel의 답변으로 확장됩니다. 가로 또는 세로 스크롤 막대에 대한 답변을 반환합니다.

(function($) {
    $.fn.hasScrollBar = function() {
        var e = this.get(0);
        return {
            vertical: e.scrollHeight > e.clientHeight,
            horizontal: e.scrollWidth > e.clientWidth
        };
    }
})(jQuery);

예:

element.hasScrollBar()             // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical    // Returns true/false
element.hasScrollBar().horizontal  // Returns true/false


답변

element.scrollHeight 가 필요합니다 . 와 비교하십시오 $(element).height().


답변

항목에 다음 CSS 속성 중 하나가 있는지 여부를 테스트하기 위해 jQuery 용 새 사용자 정의 : pseudo 선택기를 만들었습니다.

  1. 오버플로 : [scroll | auto]
  2. overflow-x : [스크롤 | 자동]
  3. 오버플로 -y : [scroll | auto]

다른 요소의 가장 가까운 스크롤 가능한 부모를 찾고 싶었으므로 오버플로가있는 가장 가까운 부모를 찾기 위해 또 다른 작은 jQuery 플러그인을 작성했습니다.

이 솔루션은 아마도 최고의 성능을 발휘하지 못하지만 작동하는 것처럼 보입니다. $ .scrollTo 플러그인과 함께 사용했습니다. 때로는 요소가 다른 스크롤 가능한 컨테이너 안에 있는지 여부를 알아야합니다. 이 경우 부모 스크롤 가능 요소와 창을 스크롤하고 싶습니다.

아마도 이것을 단일 플러그인으로 감싸서 psuedo 선택기를 플러그인의 일부로 추가하고 가장 가까운 (부모) 스크롤 가능한 컨테이너를 찾기 위해 ‘가장 가까운’방법을 노출해야했습니다.

누구든지 …. 여기 있습니다.

스크롤 가능한 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();
};

$ .scrollableparent () jQuery 플러그인 :

$.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();

    }

});