Programming

페이지에 세로 스크롤 막대가 있는지 감지 하시겠습니까?구조체에서 여러 이름 태그를 정의하는 방법

procodes 2020. 7. 19. 18:42
반응형

페이지에 세로 스크롤 막대가 있는지 감지 하시겠습니까?


현재 페이지 / 창 (특정 요소가 아님)에 세로 스크롤 막대가 있는지 확인하기 위해 간단한 JQ / JS를 원합니다.

인터넷 검색은이 기본 기능에 대해 지나치게 복잡해 보이는 것을 제공합니다.

이것을 어떻게 할 수 있습니까?


$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});

이 시도:

var hasVScroll = document.body.scrollHeight > document.body.clientHeight;

그러나 세로 scrollHeight가 볼 수있는 내용의 높이보다 큰 경우에만 알려줍니다. hasVScroll변수에는 true 또는 false가 포함됩니다.

보다 철저한 검사가 필요한 경우 위 코드에 다음을 추가하십시오.

// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible" 
             || cStyle.overflowY == "visible"
             || (hasVScroll && cStyle.overflow == "auto")
             || (hasVScroll && cStyle.overflowY == "auto");

이전 답변을 시도했지만 $ ( "body"). height ()가 전체 HTML 높이를 나타내는 것은 아닙니다.

다음과 같이 솔루션을 수정했습니다.

// Check if body height is higher than window height :) 
if ($(document).height() > $(window).height()) { 
    alert("Vertical Scrollbar! D:"); 
} 

// Check if body width is higher than window width :) 
if ($(document).width() > $(window).width()) { 
    alert("Horizontal Scrollbar! D:<"); 
} 

이 질문을 죽음에서 다시 가져 오자;) Google이 간단한 해결책을 제시하지 않는 이유가 있습니다. 특수한 경우와 브라우저 문제는 계산에 영향을 미치며, 이는 사소한 것처럼 보이지 않습니다.

불행히도 여기까지 설명한 솔루션에 문제가 있습니다. 나는 그것들을 전혀 비난하려는 것이 아닙니다. 그것들은 훌륭한 출발점이며보다 강력한 접근법에 필요한 모든 주요 속성을 터치합니다. 그러나 다른 답변에서 코드를 복사하여 붙여 넣는 것은 좋지 않습니다.

  • 신뢰할 수있는 브라우저 간 방식으로 배치 된 컨텐츠의 효과를 캡처하지 않습니다. 본문 크기를 기준으로 한 답변은 이것을 완전히 놓칩니다 (본문은 자체적으로 배치되지 않는 한 해당 내용의 오프셋 상위가 아닙니다). 그리고 그 답변을 확인 $( document ).width()하고 jQuery의 문서 크기에 대한 버그가있는 탐지에.height() 빠지게 됩니다.
  • window.innerWidth브라우저가 지원하는 경우 에 의존 하면 코드가 모바일 브라우저에서 스크롤 막대의 너비가 일반적으로 0 인 스크롤 막대를 감지하지 못합니다. 일시적으로 오버레이로 표시되며 문서에서 공간을 차지하지 않습니다. . 모바일에서 확대하는 것도 그런 방식으로 문제가됩니다 (긴 이야기).
  • 사람들이 명시 적으로 htmlbody요소 의 오버플 로를 기본값이 아닌 값 으로 설정하면 감지가 중단 될 수 있습니다 (그러면 어떤 일이 발생하는지는 이 설명을 참조하십시오 ).
  • 대부분의 답변에서 본문 패딩, 경계 또는 여백은 감지되지 않으며 결과가 왜곡됩니다.

"정상 작동하는"(기침) 해결책을 찾는 데 상상했던 것보다 더 많은 시간을 보냈습니다. 내가 함께 올라와있다 알고리즘은 이제 플러그인의 일부입니다 jQuery.isInView 노출, 방법 . 원한다면 소스를 살펴보십시오 ..hasScrollbar

페이지를 완전히 제어하고 알 수없는 CSS를 처리 할 필요가없는 시나리오에서는 플러그인을 사용하는 것이 너무 과도 할 수 있습니다. 그러나 알 수없는 환경에서 신뢰할 수있는 결과가 필요한 경우 여기에 설명 된 솔루션으로는 충분하지 않다고 생각합니다. 잘 테스트 된 플러그인-내 또는 다른 사람을 사용하는 것이 좋습니다.


이것은 나를 위해 일했다 :

function hasVerticalScroll(node){
    if(node == undefined){
        if(window.innerHeight){
            return document.body.offsetHeight> window.innerHeight;
        }
        else {
            return  document.documentElement.scrollHeight > 
                document.documentElement.offsetHeight ||
                document.body.scrollHeight>document.body.offsetHeight;
        }
    }
    else {
        return node.scrollHeight> node.offsetHeight;
    }
}

몸에는을 사용하십시오 hasVerticalScroll().


var hasScrollbar = window.innerWidth > document.documentElement.clientWidth;

페이지에 세로 스크롤 막대가 있는지 이러한 솔루션 중 어느 것도 알려주지 않습니다.

window.innerWidth - document.body.clientWidth스크롤바의 너비를 알려줍니다. 이것은 IE9 + (더 작은 브라우저에서는 테스트되지 않음)에서 작동해야합니다. (또는 질문에 엄격히 대답하기 위해!!(window.innerWidth - document.body.clientWidth)

Why? Let's say you have a page where the content is taller than the window height and the user can scroll up/down. If you're using Chrome on a Mac with no mouse plugged in, the user will not see a scrollbar. Plug a mouse in and a scrollbar will appear. (Note this behaviour can be overridden, but that's the default AFAIK).


I found vanila solution

var hasScrollbar = function() {
  // The Modern solution
  if (typeof window.innerWidth === 'number')
    return window.innerWidth > document.documentElement.clientWidth

  // rootElem for quirksmode
  var rootElem = document.documentElement || document.body

  // Check overflow style property on body for fauxscrollbars
  var overflowStyle

  if (typeof rootElem.currentStyle !== 'undefined')
    overflowStyle = rootElem.currentStyle.overflow

  overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow

    // Also need to check the Y axis overflow
  var overflowYStyle

  if (typeof rootElem.currentStyle !== 'undefined')
    overflowYStyle = rootElem.currentStyle.overflowY

  overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY

  var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight
  var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)
  var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'

  return (contentOverflows && overflowShown) || (alwaysShowScroll)
}


    <script>
    var scrollHeight = document.body.scrollHeight;
    var clientHeight = document.documentElement.clientHeight;
    var hasVerticalScrollbar = scrollHeight > clientHeight;

    alert(scrollHeight + " and " + clientHeight); //for checking / debugging.
    alert("hasVerticalScrollbar is " + hasVerticalScrollbar + "."); //for checking / debugging.
    </script>

This one will tell you if you have a scrollbar or not. I've included some information that may help with debugging, which will display as a JavaScript alert.

Put this in a script tag, after the closing body tag.


I wrote an updated version of Kees C. Bakker's answer:

const hasVerticalScroll = (node) => {
  if (!node) {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight
    }
    return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
      || (document.body.scrollHeight > document.body.offsetHeight)
  }
  return node.scrollHeight > node.offsetHeight
}

if (hasVerticalScroll(document.querySelector('body'))) {
  this.props.handleDisableDownScrollerButton()
}

The function returns true or false depending whether the page has a vertical scrollbar or not.

For example:

const hasVScroll = hasVerticalScroll(document.querySelector('body'))

if (hasVScroll) {
  console.log('HAS SCROLL', hasVScroll)
}

I use

public windowHasScroll()
{
    return document.body.clientHeight > document.documentElement.clientHeight;
}

Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:

if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')

If you also need to know the scrollbar width:

vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;

Other solutions didn't work in one of my projects and I've ending up checking overflow css property

function haveScrollbar() {
    var style = window.getComputedStyle(document.body);
    return style["overflow-y"] != "hidden";
}

but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.

참고URL : https://stackoverflow.com/questions/2146874/detect-if-a-page-has-a-vertical-scrollbar

구조체에서 여러 이름 태그를 정의하는 방법


mongo 데이터베이스에서 항목을 가져와야하므로 이와 같은 구조체를 정의했습니다.

type Page struct {
    PageId string                 `bson:"pageId"`
    Meta   map[string]interface{} `bson:"meta"`
}

이제 JSON으로 인코딩해야하지만 필드를 대문자로 인코딩합니다 (pageId 대신 PageId를 얻음). 따라서 JSON의 필드 태그도 정의해야합니다. 나는 이것과 같은 것을 시도했지만 작동하지 않았다 :

type Page struct {
    PageId string                 `bson:"pageId",json:"pageId"`
    Meta   map[string]interface{} `bson:"meta",json:"pageId"`
}

그렇다면 어떻게 할 수 있습니까? 구조체에서 여러 이름 태그를 정의합니까?


reflect패키지 문서에 나와 있습니다 .

일반적으로 태그 문자열은 선택적으로 공백으로 구분 된 키 : "값"쌍으로 연결됩니다. 각 키는 공백 (U + 0020 ''), 따옴표 (U + 0022 ' "') 및 콜론 (U + 003A ':') 이외의 비 제어 문자로 구성된 비어 있지 않은 문자열입니다. U + 0022 ' "'문자 및 Go 문자열 리터럴 구문을 사용합니다.

태그 문자열 구분 기호로 쉼표 대신 공백을 사용해야합니다.

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"meta"`
}

수락 된 답변 주셔서 감사합니다.

아래는 나와 같은 게으른 사람들을위한 것입니다.

부정확

type Page struct {
    PageId string                 `bson:"pageId",json:"pageId"`
    Meta   map[string]interface{} `bson:"meta",json:"pageId"`
}

옳은

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"pageId"`
}

참고 URL : https://stackoverflow.com/questions/18635671/how-to-define-multiple-name-tags-in-a-struct

반응형