Dom element 표시되어 있는지 확인하십시오.

내가 할 수 있는 요소를 확인하는 방식으로 유지됩니까 표시되는지를 순결케 JS (no jQuery)?

그러므로, 예를 들어, 이 페이지: 성능 여러 형태의 사각 튜브를 지닌 r 위에 마우스를 놓으면 솔루션 (상단 메뉴에서) 계약을 맺은 것은 처음부터 나타나지만, 창이 나타납니다. Html 에서 볼 수 있는 것은 아니다.

그래서 DOM element, 주어진 경우 방관하겠나 표시되는지를 어떻게 확인할 수 있습니까? 내가 시도했다.

window.getComputedStyle(my_element)['display']);

하지만, t # 39 apc® doesn& 것으로 보인다. 그 친구는 내가 할 수 있는 속성을 선택합니다. 있어서는 my mind:

display !== 'none'
visibility !== 'hidden'

제가 다른 키프레임과 수 없습니다.

질문에 대한 의견 (4)
해결책

이 매든 문서용으로 에 따르면, '속성' null 'it' s # 39 element& 프세파렌트 반환되므로 때마다, 또는 해당 부모, 숨겨짐 디스플레이 스타일을 통해 재산이잖아 그냥 smartupdate 작업자쪽에서 요소점 isn& # 39, t 고정식입니다. 이를 확인하기 위해 스크립트입니다 없을 경우 포지션: '요소, 고정, 페이지에 다음과 같습니다.

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    return (el.offsetParent === null)
}
    • %S/dbase/ext_table. 할 수 있는 반면, 이 경우 고정 요소를 포지셔닝하십시오 프레젠테이션이든 포착됨 검색, 안타깝게도 사용해야 할 수 있습니다 (서서히) '빈다우스게츠롬푀테트슈타일 ()'. 이 경우 해당 기능을 사용할 수 있습니다.
// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

옵션 # 2 는 아마 조금 더 쉽게 차지하기 때문에 자세한 건 너무 좋은 거래 속도가 느리며, but I bet 모서리까지 등 여러 차례 받지 않을 경우, 그래서 반복하려면 이 작업을 위해 최선을 다하고 있습니다.

해설 (19)

일부 다른 모든 솔루션을 가져다줄래요 상황이 발생했다.

지켜보리니 오토메이티드 http://www1.itrc. 깨고 우승

http://plnkr.co/edit/6CSCA2fe4Gqt4jCBP2wu? p = 미리봅니다

결국, 내가 하고 있는 가장 좋은 해결책은 .is (& # 39, :visible& # 39;) $ (elem) '' = 그러나 javascript 순결케 아니다. 이는 포함한다.

그래서 내가 원했던 안을 때 자신의 소스 and found

jQuery.expr.filters.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

이것은 출처: https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js

해설 (3)

39 you& 사용자가 관심을 보이는 경우, re:

function isVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity < 0.1) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
        y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };
    if (elemCenter.x < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y < 0) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === elem) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

거친 (mocha-ae 용어를 사용하여):

describe.only('visibility', function () {
    let div, visible, notVisible, inViewport, leftOfViewport, rightOfViewport, aboveViewport,
        belowViewport, notDisplayed, zeroOpacity, zIndex1, zIndex2;
    before(() => {
        div = document.createElement('div');
        document.querySelector('body').appendChild(div);
        div.appendChild(visible = document.createElement('div'));
        visible.style       = 'border: 1px solid black; margin: 5px; display: inline-block;';
        visible.textContent = 'visible';
        div.appendChild(inViewport = visible.cloneNode(false));
        inViewport.textContent = 'inViewport';
        div.appendChild(notDisplayed = visible.cloneNode(false));
        notDisplayed.style.display = 'none';
        notDisplayed.textContent   = 'notDisplayed';
        div.appendChild(notVisible = visible.cloneNode(false));
        notVisible.style.visibility = 'hidden';
        notVisible.textContent      = 'notVisible';
        div.appendChild(leftOfViewport = visible.cloneNode(false));
        leftOfViewport.style.position = 'absolute';
        leftOfViewport.style.right = '100000px';
        leftOfViewport.textContent = 'leftOfViewport';
        div.appendChild(rightOfViewport = leftOfViewport.cloneNode(false));
        rightOfViewport.style.right       = '0';
        rightOfViewport.style.left       = '100000px';
        rightOfViewport.textContent = 'rightOfViewport';
        div.appendChild(aboveViewport = leftOfViewport.cloneNode(false));
        aboveViewport.style.right       = '0';
        aboveViewport.style.bottom       = '100000px';
        aboveViewport.textContent = 'aboveViewport';
        div.appendChild(belowViewport = leftOfViewport.cloneNode(false));
        belowViewport.style.right       = '0';
        belowViewport.style.top       = '100000px';
        belowViewport.textContent = 'belowViewport';
        div.appendChild(zeroOpacity = visible.cloneNode(false));
        zeroOpacity.textContent   = 'zeroOpacity';
        zeroOpacity.style.opacity = '0';
        div.appendChild(zIndex1 = visible.cloneNode(false));
        zIndex1.textContent = 'zIndex1';
        zIndex1.style.position = 'absolute';
        zIndex1.style.left = zIndex1.style.top = zIndex1.style.width = zIndex1.style.height = '100px';
        zIndex1.style.zIndex = '1';
        div.appendChild(zIndex2 = zIndex1.cloneNode(false));
        zIndex2.textContent = 'zIndex2';
        zIndex2.style.left = zIndex2.style.top = '90px';
        zIndex2.style.width = zIndex2.style.height = '120px';
        zIndex2.style.backgroundColor = 'red';
        zIndex2.style.zIndex = '2';
    });
    after(() => {
        div.parentNode.removeChild(div);
    });
    it('isVisible = true', () => {
        expect(isVisible(div)).to.be.true;
        expect(isVisible(visible)).to.be.true;
        expect(isVisible(inViewport)).to.be.true;
        expect(isVisible(zIndex2)).to.be.true;
    });
    it('isVisible = false', () => {
        expect(isVisible(notDisplayed)).to.be.false;
        expect(isVisible(notVisible)).to.be.false;
        expect(isVisible(document.createElement('div'))).to.be.false;
        expect(isVisible(zIndex1)).to.be.false;
        expect(isVisible(zeroOpacity)).to.be.false;
        expect(isVisible(leftOfViewport)).to.be.false;
        expect(isVisible(rightOfViewport)).to.be.false;
        expect(isVisible(aboveViewport)).to.be.false;
        expect(isVisible(belowViewport)).to.be.false;
    });
});
해설 (2)
  • 이 : 도움이 될 수 있습니다 대부분의 it on 이들보 포지셔닝하십시오 프세레프트 확인 후 왼쪽 숨김니다 요소점 포지셔닝하면 재산이잖아 Jquery 사용하려면 &lt 확인 됩니다. (http://api.jquery.com/visible-selector/), a href = &quot &quot &gt /a&gt :visible&l ;;;; 선택기를 및 내려받습니다 가시도로 상태를 요소.

  • HTML :*

<div id="myDiv">Hello</div>
  • CSS :*

#myDiv{
   position:absolute;
   left : -2000px;
}


#myDiv{
    visibility:hidden;
}
  • javaScript :*
var myStyle = document.getElementById("myDiv").offsetLeft;

if(myStyle < 0){
     alert("Div is hidden!!");
}
  • jQuery :*
if(  $("#MyElement").is(":visible") == true )
{  
     alert("Div is hidden!!");        
}

, (http://jsfiddle.net/codeSpy/Nr99p/&quot), a href = &quot &lt &gt jsfiddle*&l /a>;;;

해설 (7)

Jquery 는 동일한 코드를 사용할 수 있다.

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

따라서 함수.

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

마치 내 Win/IE10 Linux/Firefox.45 Linux/Chrome.52. 작동됨 매력,

덕분에 많은 없이 jQuery jQuery!

해설 (3)

위의 결합 몇 대답:

function isVisible (ele) {
    var style = window.getComputedStyle(ele);
    return  style.width !== "0" &&
    style.height !== "0" &&
    style.opacity !== "0" &&
    style.display!=='none' &&
    style.visibility!== 'hidden';
}

앨릭스 말하였노라 일부 제품을 보다 느린 경우 이 같은 다른 옵션을 더 잘 알 수 있습니다, re 찾고 있지만 구체적으로 어떤 you& # 39 이 모든 주요 방법이 숨길지 요소를 잘 합니다.

하지만 어떤 들려주시겠습니까 공동체의식이 표시로 당신꺼에요. 예를 들어, div& 그냥 # 39 의 높이에 따라 내용을 볼 수 있지만 여전히 오버플로입니다 특성는 0px 설정할 수 있습니다. # 39 의 콘텐츠를 만들 수 있는데, 또는 div& 같은 색상의 배경 때문에 사용자 페이지에 렌더링됩니다 그래도 볼 수 없습니다. 가르보는 화면 또는 뒤에 숨겨진 다른 div 로 이동할 수 있습니다 또는 div 에 될 수 있지만 여전히 보이지 않는 내용 또는 it& # 39 국경 가시적입니다. 특정 범위 &quot visible"; 는 주관적 용어입니다.

해설 (3)

만약 요소가 있지만, 일부 일반 가시적입니다 (디스플레이, 블록 및 비시빌티 가시적입니다:) 및 모피쳐 컨테이너입니다 숨겨짐 관심용 클리엔트위데스 클리나이트 체크 하는 이용할 수 있다.

22 874 {{{000}}}

프룬커 (여기를 클릭)

해설 (1)

39, ve got a 에 비해 더 강력한 솔루션이므로 i& [AlexZ& # 39 의 솔루션을 제크롬푀테트슈타일 ()] [1] # 39, & # 39 한 때 포지셔닝하십시오 fixed& 있다. 결단만 있으면 무시하려면 요소를 일부 면쪽 건 (확인란 의견):

function isVisible(el) {
    /* offsetParent would be null if display 'none' is set.
       However Chrome, IE and MS Edge returns offsetParent as null for elements
       with CSS position 'fixed'. So check whether the dimensions are zero.

       This check would be inaccurate if position is 'fixed' AND dimensions were
       intentionally set to zero. But..it is good enough for most cases.*/
    if (!el.offsetParent && el.offsetWidth === 0 && el.offsetHeight === 0) {
        return false;
    }
    return true;
}

[1]: # 21696585 https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom/21696585

때는기대어 참고: 엄밀히 말하면, &quot visibility"; 먼저 정의해야 합니다. 저의 경우는 요소를 고려할 때, 나는 내가 할 수 있는 방법 / 속성이 가시적입니다 deltamove 모두실행 DOM 없이 이 문제 (경우에도 # 39, & # 39 는 0 또는 CSS 가시도로 속성은 불투명도와 hidden&. 등).

해설 (0)

39 we& 경우, 수집, 절 잊지 말고 그냥 기본적인 방법을 감지 가시도로 re:

opacity > 0.01; // probably more like .1 to actually be visible, but YMMV

그리고 어떻게 해야 할지 소유하십시오 속성:

element.getAttribute(attributename);

따라서 너회의 예:

document.getElementById('snDealsPanel').getAttribute('visibility');

하지만 뭐? # 39 이 doesn& 목마르겠구나 빗나갔다. # 39, 모든 것을 알 수 없는 업데이트되는 가시도로 여바바 closer 와 you& 표시됨과 요소에 대한 속성 '스타일' 을 사용하지만, 재산이잖아 이 중 하나는 일을 하고, re you& # 39 많은 문제가 있다. 등이: # 39, s, t # 39 너회가 can& there& 실제로 볼 수 있다고 해서, 그냥 뭔가 요소에 때문에 해당 가시도로, 디스플레이, 불투명도의 모두 정확한 값을. 아직 부족한 콘텐트, 높이와 폭이 지정값이 없는 경우가 있다. 다른 객체에는 가릴 수 있을 것입니다. 자세한 내용은 구글 검색을 통해 빠르게 , 심지어 dm_ownerdm_owner 라리브러리 시도하시려면 문제 해결. (이메프)

이 질문에 답을 중복 사용할 수 있는 우수한 정보정의다음 체크아웃합니다 insight 를 포함한 몇몇 내렸노라 존 레식. 그러나 한 도왔으매 I& 표준 사용자의 특정 활용 약간 다릅니다. # 39, ll 자제할 플래깅:

(편집: OP 말합니다 HE& # 39, S, T # 39 아래 ISN& 스크래핑 페이지, 그들을 도왔으매 만들지 않을 경우) 더 나은 쪽을? 항상 가시도로 모델을 만들 수 있는 요소 모델 특성 및 바인딩해야 가시도로 전략국제문제연구소 (csis) 와 각 높여줍니까 것만큼 ng 보기. 그렇게 할 수 있는 도구를 사용하여 운영까지도: Js, 각도, 일반 그러든지요 아직 더 시간이 지남에 따라 you& # 39, ll, DOM 구축상의 변경할 수 있습니다, 하지만 항상 모델에서 DOM 대신 시/도 읽을 수 있다. 판독값 너회의 거짓하였으니 DOM 에서 잘못되었습니다. 느리고. 내가 긁어줄게 모델용 확인할 수 있도록 하기 위한 시스템 구축을 믿고 DOM 스테이드 반영된 모델이다. (및 테스트 자동화를 통해 확인하기 위해 가정).

해설 (1)

그냥 ' ()' 의 경우에 따라 일할 수 있는 제바우드링클리앵 트레스 참조입니다 점에 유의해야 합니다.

예를 들어, '디스플레이를 사용하여 간단한 숨겨짐 요소점 확인합니다. 없음 '이 같은 다소 볼 수 있었다.

var box = element.getBoundingClientRect();
var visible = box.width && box.height;

또한, 이 역시 되어 있기 때문에 너비 닫히지만 제로 높이 및 포지션: 고정식입니다 '건으로 집계됐다. 그러나 보고하지 불지옥으 요소이면 숨겨짐 함께 '불투명도의: 0 '또는' 가시도로: 숨겨짐 ' (그러나 괜찼습니다 다시그것들을' 프세파렌트 ').

해설 (3)

그래서 내가 발견된 가장 실현 가능한 방법:

function visible(elm) {
  if(!elm.offsetHeight && !elm.offsetWidth) { return false; }
  if(getComputedStyle(elm).visibility === 'hidden') { return false; }
  return true;
}

이는 이런 사실을 기반으로.

  • 'A' 디스플레이: 없음 '요소 (심지어 네스트된) 한 높이, 폭 disk_b_s10database doesn& # 39 없다.
  • '표시 유형' 는 '숨겨진' 대해서도 네스트된 요소.

그래서 필요 없음 '또는' 테스트 '는' up in the DOM 진단트리는 프세파렌트 루프을 테스트하려면 모피쳐 있는 가시도로: 숨겨짐 '. 심지어 인터넷 익스플로러 9 이 노력해야 합니다.

수도 있을 것 '불투명도의 경우 있습니다. 0 '과 축소됨 요소 () 는 높이 너버 아님) 또는 그 반대의 경우도 마찬가지입니다 -) 는 별로 가시적입니다 중 하나. 그런데 다시 당 않는 말하도다 감춰집니다.

해설 (0)

39 의 오하드 navon& 조금 아니라 그 답이 있다.

만약 우리가 속한 요소가 다른 요소를 중심에 won& # 39, t 파일을 찾을 수 있습니다.

그래서 요소의 것을 확인할 수 있도록 한 점 볼 수 있다.

function isElementVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity === 0) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    var elementPoints = {
        'center': {
            x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
            y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
        },
        'top-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().top
        },
        'top-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().top
        },
        'bottom-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().bottom
        },
        'bottom-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().bottom
        }
    }

    for(index in elementPoints) {
        var point = elementPoints[index];
        if (point.x < 0) return false;
        if (point.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
        if (point.y < 0) return false;
        if (point.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
        let pointContainer = document.elementFromPoint(point.x, point.y);
        if (pointContainer !== null) {
            do {
                if (pointContainer === elem) return true;
            } while (pointContainer = pointContainer.parentNode);
        }
    }
    return false;
}
해설 (0)

39 의 향상합니다 @Guy Messika& 오토메이티드 그들위에 의 경우, 분할 및 거짓값 돌아온 센터 point& # 39. X 는 &lt. 0 으로 잘못 요소점 오른쪽면 들어갈 수 있으며 이 경치말이야 # 39 의 here& 수정:

private isVisible(elem) {
    const style = getComputedStyle(elem);

    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if ((style.opacity as any) === 0) return false;

    if (
        elem.offsetWidth +
        elem.offsetHeight +
        elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0
    ) return false;

    const elementPoints = {
        center: {
            x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
            y: elem.getBoundingClientRect().top + elem.offsetHeight / 2,
        },
        topLeft: {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().top,
        },
        topRight: {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().top,
        },
        bottomLeft: {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().bottom,
        },
        bottomRight: {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().bottom,
        },
    };

    const docWidth = document.documentElement.clientWidth || window.innerWidth;
    const docHeight = document.documentElement.clientHeight || window.innerHeight;

    if (elementPoints.topLeft.x > docWidth) return false;
    if (elementPoints.topLeft.y > docHeight) return false;
    if (elementPoints.bottomRight.x < 0) return false;
    if (elementPoints.bottomRight.y < 0) return false;

    for (let index in elementPoints) {
        const point = elementPoints[index];
        let pointContainer = document.elementFromPoint(point.x, point.y);
        if (pointContainer !== null) {
            do {
                if (pointContainer === elem) return true;
            } while (pointContainer = pointContainer.parentNode);
        }
    }
    return false;
}
해설 (0)

코드 (포함한다 (http://code.jquery.com/jquery-1.11.1.js) 에는 이시든 매개 변수

var isHidden = function( elem, el ) {
    // isHidden might be called from jQuery#filter function;
    // in that case, element will be second argument
    elem = el || elem;
    return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};

그래서 it looks like there is an 소유자에게도 관련된 문서를 추가 확인

이 경우 다음과 같은 경우 가로채기 정말 궁금하다.

  1. 뒤에 숨겨진 요소가 다른 요소를 기반으로 진데스
  2. 이를 통해 전체 투명도로 보이지 않는 요소가 있다.
  3. 화면 밖에서 포지셔닝되어 요소 (즉, 왼쪽: 1000px)
  4. 요소 숨김 기능:
  5. 요소를 사용한 표시 없음 (none)
  6. 텍스트 또는 하위 요소를 볼 수 없는 요소
  7. 0 으로 설정되어 있는 요소가 높이나 너비에
해설 (0)

진정한 되돌려줍니다 요소 및 그 조상들은 이 경우에만 볼 수 있습니다. '스타일' 와 '가시도로 살펴보고 뿐이다' 디스플레이 속성:

    var isVisible = function(el){
        // returns true iff el and all its ancestors are visible
        return el.style.display !== 'none' && el.style.visibility !== 'hidden'
        && (el.parentElement? isVisible(el.parentElement): true)
    };
해설 (1)

39 의 코드는 here& 작성했습니까 가운데 유일한 가시적입니다 비슷한 요소, 내가 찾는 등 몇 가지 값을 되돌려줍니다 &quot class"; 없이 속성을 포함한다.

  // Build a NodeList:
  var nl = document.querySelectorAll('.myCssSelector');

  // convert it to array:
  var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));

  // now find the visible (= with offsetWidth more than 0) item:
  for (i =0; i < myArray.length; i++){
    var curEl = myArray[i];
    if (curEl.offsetWidth !== 0){
      return curEl.getAttribute("class");
    }
  }
해설 (0)

이 is what I did.

  • HTML &amp. CSS. 기본적으로 한 요소점 감춰집니다 *



Click Me

<p id="demo" style ="visibility: hidden;">Hello World</p> 


  • JavaScript: 또 가시도로 숨겨졌거나 not:* 코드 여부를 확인할 수 있다.
<script>
function myFunction() {
   if ( document.getElementById("demo").style.visibility === "hidden"){
   document.getElementById("demo").style.visibility = "visible";
   }
   else document.getElementById("demo").style.visibility = "hidden";
}
</script>
해설 (0)

이는 정보기술 (it) 등 모든 가시도로 css 속성을 쉽게 확인할 수 있습니다.

html:

<div id="element">div content</div>

css.

#element
{
visibility:hidden;
}

javascript:

var element = document.getElementById('element');
 if(element.style.visibility == 'hidden'){
alert('hidden');
}
else
{
alert('visible');
}

Css 작동하잖아 모든 재산과 매우 다용도이면서도 믿을 수 있습니다.

해설 (0)