How To Adjust a User's view using Javascript a

2019-08-01 00:16发布

I've got the following Script:

<div id=tbl name=tbl style="overflow:hidden;display:none">
<script language="JavaScript" type="text/javascript">
<!--

function sizeTbl() {

    var tbl = document.getElementById('tbl');
    var icon = document.getElementById('toggle-table');
    if (icon.src === 'up_arrow.png'){

        tbl.style.display = 'none';
        icon.src = 'down_arrow.png';
    }
    else {
        tbl.style.display = 'block';
        icon.src = 'up_arrow.png';    
    }
}

// -->
</script> 
<br>

<a href="javascript:sizeTbl()"><img src="down_arrow.png" id="toggle-table"></a>

This does exactly what I want by having a section of a website hidden from a user's view until the click the "down" arrow. Then when they click said arrow, the content expands and the "down" arrow changes to an "up" arrow. Once the user hits the "up" arrow, the content hides again and the arrow returns to a "down" arrow.

The trick is that the content is quite long so when the user closes the section by hitting the "up" arrow, the section the table resides in shifts further up than the user's view. I'd like to solve that using Anchor tags so whenever either arrow is hit, the user's view is adjusted to the top of the section. Any ideas how I can go about that using the current setup?

2条回答
看我几分像从前
2楼-- · 2019-08-01 00:53

have you tried using slideUp and slideDown with jQuery?

查看更多
走好不送
3楼-- · 2019-08-01 00:54

EDIT:

I'm going to suggest window.scrollto() JsFiddle Instead of using an anchor with a hash, use any element with an id

function sizeTbl() {
    var tbl = document.getElementById('tbl');
    var icon = document.getElementById('toggle-table');
    if (icon.innerText === 'hide'){
        tbl.style.display = 'none';
        icon.innerText = 'show';
    }
    else {
        tbl.style.display = 'block';
        icon.innerText = 'hide';    
    }
    var x = getOffset( document.getElementById('bottom') );
    console.log(x);
    window.scrollTo(x.left, x.top); // values are x,y-offset
}

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
} 
查看更多
登录 后发表回答