programing

요소가 화면 밖에 있는지 확인하는 방법

subpage 2023. 9. 1. 20:58
반응형

요소가 화면 밖에 있는지 확인하는 방법

DIV 요소가 화면에서 떨어지지 않는지 jQuery에 확인해야 합니다.요소는 CSS 속성에 따라 표시되고 표시되지만 의도적으로 화면 밖에 배치될 수 있습니다.

position: absolute; 
left: -1000px; 
top: -1000px;

는 jQuery jQuery를 할 수 .:visible요소의 높이와 너비가 0이 아닌 선택기입니다.

저는 화려한 것을 하고 있지 않습니다. 절대 위치 배치는 내 Ajax 프레임워크가 일부 위젯의 숨기기/표시를 구현하는 방법입니다.

"오프스크린"의 정의에 따라 다릅니다.뷰포트 내에 있습니까, 아니면 페이지의 정의된 경계 내에 있습니까?

Element.getBoundingClientRect()사용하면 요소가 뷰포트의 경계 내에 있는지 여부(즉, 화면상 또는 화면 밖)를 쉽게 감지할 수 있습니다.

jQuery.expr.filters.offscreen = function(el) {
  var rect = el.getBoundingClientRect();
  return (
           (rect.x + rect.width) < 0 
             || (rect.y + rect.height) < 0
             || (rect.x > window.innerWidth || rect.y > window.innerHeight)
         );
};

그런 다음 여러 가지 방법으로 사용할 수 있습니다.

// returns all elements that are offscreen
$(':offscreen');

// boolean returned if element is offscreen
$('div').is(':offscreen');

사용자가 브라우저 스크롤 위치를 고려하여 요소가 브라우저의 보이는 뷰포트 내에 있는지 여부를 테스트할 수 있는 jQuery 플러그인이 있습니다.

$('#element').visible();

부분적인 가시성도 확인할 수 있습니다.

$('#element').visible( true);

한 가지 단점은 수직 위치 설정/스크롤에서만 작동한다는 것입니다. 그러나 수평 위치 설정을 조합에 추가하는 것은 충분히 쉬울 것입니다.

플러그인이 뷰 포트를 벗어나는지 확인할 필요가 없습니다.

var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var d = $(document).scrollTop();

$.each($("div"),function(){
    p = $(this).position();
    //vertical
    if (p.top > h + d || p.top > h - d){
        console.log($(this))
    }
    //horizontal
    if (p.left < 0 - $(this).width() || p.left > w){
        console.log($(this))
    }
});

여기 있는 모든 제안된 해결책에서 몇 가지 문제점을 발견했습니다.

  • 전체 요소를 화면에 표시할지 또는 일부 요소만 표시할지 선택할 수 있어야 합니다.
  • 요소가 창보다 높고 브라우저 창을 덮으면 제안된 솔루션이 실패합니다.

다음과 같은 솔루션이 있습니다.jQuery .fn 및 인스턴스 함수expression제가 할 수 있는 것보다 더 많은 변수를 제 함수 안에 만들었지만, 복잡한 논리적 문제에 대해서는 더 작고 명확한 이름을 가진 조각들로 나누는 것을 좋아합니다.

는 중용사를 합니다.getBoundingClientRect스크롤 위치에 상관없이 뷰포트에 상대적으로 요소 위치를 반환하는 방법

용도:

$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false 

출처:

$.fn.isOnScreen = function(partial){

    //let's be sure we're checking only one element (in case function is called on set)
    var t = $(this).first();

    //we're using getBoundingClientRect to get position of element relative to viewport
    //so we dont need to care about scroll position
    var box = t[0].getBoundingClientRect();

    //let's save window size
    var win = {
        h : $(window).height(),
        w : $(window).width()
    };

    //now we check against edges of element

    //firstly we check one axis
    //for example we check if left edge of element is between left and right edge of scree (still might be above/below)
    var topEdgeInRange = box.top >= 0 && box.top <= win.h;
    var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;

    var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
    var rightEdgeInRange = box.right >= 0 && box.right <= win.w;


    //here we check if element is bigger then window and 'covers' the screen in given axis
    var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
    var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;

    //now we check 2nd axis
    var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
    var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );

    var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
    var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );

    //now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
    var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
    var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;

    return partial ? isPartiallyOnScreen : isEntirelyOnScreen;

};

$.expr.filters.onscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

$.expr.filters.entireonscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

원래 포스터는 JQuery 솔루션을 요청했지만 질문에 JavaScript 태그를 추가하여 보다 현대적인 솔루션을 추가할 수 있도록 했습니다.

TLDR: Intersection Observer API를 사용합니다.

다음은 바닐라 자바스크립트와 리액트로 만든 샌드박스 두 개를 작업 예제로 보여줍니다.

  1. 바닐라 자바스크립트 예제 샌드박스
  2. 반응 예제 샌드박스(반응 교차로 관찰자 NPM 모듈 사용)

조금 더 긴 답변:이 질문을 한 지 10년이 넘었고 당시에는 이러한 JQuery 솔루션을 사용하는 것이 타당했지만, 오늘날 우리는 더 이상 JQuery가 필요하지 않습니다.

교차로 관찰자 API는 상위 요소 또는 최상위 문서의 뷰포트와 대상 요소의 교차로 변경사항을 관찰할 수 있는 방법을 제공합니다.

사용하기 매우 쉽습니다. 먼저 관찰자를 만들고 트리거될 때 수행할 작업을 전달합니다(콜백 기능). 또한 옵션 개체도 전달합니다. 예를 들어, 이 질문의 경우 요소가 뷰포트 내에 완전히 있는지 확인하려면 값이 1인 임계값 옵션이 필요합니다. 그렇지 않으면그러면 "오프스크린"이라는 것을 알게 될 것입니다.

const doable = () => {
  //do something
}
const observer = new IntersectionObserver(doable, { threshold: 1 });

이제 전화해 보세요.observe()관찰할 요소를 전달합니다.

observer.observe(observee)

이게 좀 늦은 건 알지만 이 플러그인은 작동해야 합니다.http://remysharp.com/2009/01/26/element-in-view-event-plugin/

$('p.inview').bind('inview', function (event, visible) {
if (visible) {
  $(this).text('You can see me!');
} else {
  $(this).text('Hidden again');
}
  • 지정된 요소의 맨 위에서 거리를 가져옵니다.
  • 지정된 동일한 요소의 높이를 추가합니다.화면 상단에서 지정된 요소의 끝까지 총 숫자가 표시됩니다.
  • 그러면 총 문서 높이에서 이 값을 빼면 됩니다.

    jQuery(function () {
        var documentHeight = jQuery(document).height();
        var element = jQuery('#you-element');
        var distanceFromBottom = documentHeight - (element.position().top + element.outerHeight(true));
        alert(distanceFromBottom)
    });
    

다음을 사용하여 디바이드의 위치를 확인할 수 있습니다.$(div).position()왼쪽 및 위쪽 여백 속성이 0보다 작은지 확인합니다.

if($(div).position().left < 0 && $(div).position().top < 0){
    alert("off screen");
}

언급URL : https://stackoverflow.com/questions/8897289/how-to-check-if-an-element-is-off-screen

반응형