How to not move page if html element is on screen?

I don't use jQuery. Can this be solved without it ?

I have only 1 HTML / JavaScript / (CSS) page. It contains links that reference html elements on the very same page. The page has a automatic vertical scrollbar because it is long. I need my event handler for link clicks to check if the referenced element is on the screen at the moment of the click. If it is there the page should not change position. Is that possible and how ?

  • check if on screen
  • don't move page
  • This code is a simple example that the page jumps so that the "hello world 2" is on the very top of the browser window.

    <html>
        <head>
            <script type='text/javascript' language='javascript'>
                function onLinkClick(id)
                { }
            </script>
        </head>
        <body>
            <div id="id1">hello world 1</div>
                <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
            <div id="id2">hello world 2</div>
            <a href="#id2" onclick="onLinkClick('id2')">link</a>
            <div id="id3">hello world 3</div>
                <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        </body>
    </html>
    

    did you tried

    getElementByTagName() ???


    Ok, I solved it by myself (yes with some help of the referenced duplicate question). Using no jQuery:

    function isElementVisible(element)
    {
        var posTop = 0;
        var temp = element;
        while (temp)
        {
            posTop += temp.offsetTop;
            temp = temp.offsetParent;
        }
        var posBottom = posTop + element.offsetHeight;
        var visibleTop = document.body.scrollTop;
        var visibleBottom = visibleTop + window.innerHeight;
        return ((posBottom >= visibleTop) && (posTop <= visibleBottom));
    }
    
    function onLinkClick(id)
    {
        var x = document.getElementById(id);
        if (isElementVisible(x))
            // prevent page to be scrolled up or down
            event.preventDefault();
    }
    
    链接地址: http://www.djcxy.com/p/83606.html

    上一篇: jQuery队列fadeIn()滚动

    下一篇: 如果HTML元素在屏幕上,如何不移动页面?