Подтвердить что ты не робот

Могу ли я определить зону просмотра пользователя в браузере?

Как вы можете видеть изображение ниже, на веб-сайте есть "A", "B", "C", "D" и "E", и пользователь может видеть только A, B и небольшие части D в браузере. Они должны потребовать прокрутки браузера, или некоторые пользователи могут иметь больший экран или более длинное окно в своем браузере, которые позволяют даже видеть элемент C.

Хорошо, мой вопрос в том, можно ли мне сообщить, что пользователь видит в своем браузере с помощью javascript? В этом элементе есть "A", "B" и "D".

enter image description here

4b9b3361

Ответ 1

Попробуйте: http://jsfiddle.net/Aj2fU/5/

$('input').click(function(){
   // check for visible divs with class 'check'   
    $('.check').each(function(){
        var pos = $(this).offset(),
            wX = $(window).scrollLeft(), wY = $(window).scrollTop(),
            wH = $(window).height(), wW = $(window).width(),
            oH = $(this).outerHeight(), oW = $(this).outerWidth();

        // check the edges
        // left, top and right, bottom are in the viewport
        if (pos.left >= wX && pos.top >= wY && 
            oW + pos.left <= wX + wW && oH + pos.top <= wY + wH )
            alert('Div #' + $(this).attr('id') + ' is fully visible');
        else // partially visible   
        if (((pos.left <= wX && pos.left + oW > wX) ||
             (pos.left >= wX && pos.left <= wX + wW)) &&
            ((pos.top <= wY && pos.top + oH > wY)   ||
             (pos.top  >= wY && pos.top  <= wY + wH)))
            alert('Div #' + $(this).attr('id') + ' is partially visible');
        else // not visible 
            alert('Div #' + $(this).attr('id') + ' is not visible');
    });        
});​

Обновлено для работы с очень широкими div. В основном это проверяет, находятся ли левый, верхний и правый нижние края divs как в видимой части экрана, так и вне области просмотра.

Ответ 2

Используя следующее, вы можете получить размер видового экрана браузера.

window.innerHeight;
window.innerWidth;

http://bit.ly/zzzVUv - При использовании Google Cache сайт не загрузился бы для меня. Исходная страница: http://www.javascripter.net/faq/browserw.htm

Если вы хотите определить, насколько далеко они прокрутили страницу, вы можете использовать

window.scrollX;   // Horizontal scrolling
window.scrollY;   // Vertical scrolling

Кроме того, я нашел объект window - window.screen. В моей системе он имеет следующие данные:

window.screen.availHeight = 994;
window.screen.availLeft = 0;
window.screen.availTop = 0;
window.screen.availWidth = 1280;
window.screen.colorDepth = 32;
window.screen.height = 1280;
window.screen.pixelDepth = 32;
window.screen.width = 1280;

Я надеюсь, что они ответят на ваш вопрос достаточно.

Ответ 3

В принципе, сначала вам нужно будет измерить размеры окна просмотра, используя оконный объект, тогда вам нужно будет пропустить каждый из элементов, которые вы хотите проверить, и рассчитать, насколько они подходят.

Смотрите пример jsfiddle для примера.

Здесь код (для потомства):

HTML:

<div id="info">
    <p class="wxh"></p>
    <p class="txl"></p>
    <p class="report"></p>
</div>

<h1>A big list!</h1>
<ul></ul>

CSS

#info{
    position: fixed;
    right: 0px;
    text-align: center;
    background: white;
    border: 2px solid black;
    padding: 10px;
}

JS:

    $(function(){

    $(window).bind('scroll.measure resize.measure',function(){

        // Gather together the window width, height, and scroll position.
        var winWidth = $(window).width(),
            winHeight = $(window).height(),
            winLeft = $(window).scrollLeft(),
            winTop = $(window).scrollTop(),
            winBottom = winTop + winHeight,
            winRight = winLeft + winWidth,
            inView = [];

        // Loop over each of the elements you want to check
        $('.inview').each(function(){

            // Get the elements position and dimentions.
            var pos = $(this).position(),
                width = $(this).outerWidth(),
                height = $(this).outerHeight();

            // Set bottom and right dimentions.
            pos.bottom = pos.top + height;
            pos.right = pos.left + width;

            // Check whether this element is partially within
            // the window visible area.
            if((
                pos.left >= winLeft &&
                pos.top >= winTop &&
                pos.right <= winRight &&
                pos.bottom <= winBottom
            ) || (
                pos.left >= winLeft && pos.top >= winTop && 
                pos.left <= winRight && pos.top <= winBottom
            ) || (
                pos.right <= winRight && pos.bottom <= winBottom &&
                pos.right >= winLeft && pos.bottom >= winTop
            )){
                // Change this to push the actual element if you need it.
                inView.push( $(this).text() );
            }
        });

        // For the purposes of this example, we only need the
        // first and last element, but in your application you may need all.
        var first = inView.shift(),
            last = inView.pop();

        // Show the details in the info box.
        $('#info .wxh').text( winWidth+' x '+winHeight );
        $('#info .txl').text( winTop+' x '+winLeft );
        $('#info .report').text( 'Showing from '+first+' to '+last );
    });

    // The rest is just setup stuff, to make the area scrollable.
    for( var i=0; i<100; i++ ){
        $('ul').append('<li class="inview">List item '+i+'</li>');
    }

    $(window).trigger('resize.measure');
})    ​

Ответ 4

Вы можете получить видимую область окна,

var pwidth = $(window).width();
var pheight = $(window).height();

Затем получите прокрутку документа,

$(document).scroll(function(e) {
       var top = $(this).scrollTop();       
       $("h1").html("total visible area is from:"+ top +" to "+ (pheight + top) +"px");
    });

Полный пример: http://jsfiddle.net/parag1111/kSaNp/