如何使用Javascript和Anchor标签调整用户视图 [英] How To Adjust a User's view using Javascript and Anchor tags

查看:72
本文介绍了如何使用Javascript和Anchor标签调整用户视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本:

<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.

诀窍是内容很长,因此当用户通过单击向上"箭头关闭该部分时,表所在的部分将比用户的视图向上移位.我想使用Anchor标签解决此问题,因此,每当击中任一箭头时,用户的视图都将调整到该部分的顶部.有什么想法可以使用当前设置进行操作吗?

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?

推荐答案

我将建议window.scrollto() JsFiddle 代替使用带有哈希的锚,而使用具有id的任何元素

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 };
} 

这篇关于如何使用Javascript和Anchor标签调整用户视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆