如何使用Javascript始终将窗口带到前面?

时间:2012-09-26 13:44:07

标签: javascript jquery html firefox

以下是我页面中的链接(MAIN):

<a href="log_details.jsf#MyAnchor" target="log">View details</a>

如果没有打开窗口,则会出现一个新窗口(让我们称之为LOG),并在顶部指向锚点。

如果LOG保持打开状态,用户决定返回MAIN点击其他链接

<a href="log_details.jsf#MyAnchor2" target="log">View details</a>

LOG中的位置移动到MyAnchor2,但LOG没有移到顶部。

当用户点击类似以下链接时,如何让LOG显示在顶部:

<a href="log_details.jsf#MyAnchorXXX" target="log">View details</a>

1 个答案:

答案 0 :(得分:1)

如果窗口已经打开并且Javascript中的变量log已知,那么您应该可以在窗口上调用log.focus()将其置于最前面。

修改

当您使用target属性时,它会为窗口指定一个“名称”。但是,此名称与Javascript变量是分开的。因此,在target="log"的情况下,没有与log函数一起引用的名为.focus()的对应变量。


function logLinks(){
    //Get every A tag
    var links = document.getElementsByTagName('a');
    //Iterate through the elements and...
    for(i=0; i<links.length; i++){
        //If the element has a class of 'log'
        if(links[i].className=='log'){
            //Clone it
            var dup = links[i].cloneNode(true);
            //Strip move the href elsewhere
            dup.id=dup.href; 
            dup.href='';
            //Add a click listener
            dup.addEventListener('click', function(){openLog(this.id);}, false);
            //Replace the existing element on the page
            links[i].parentNode.replaceChild(dup, links[i]);
        }
    }
}

function openLog(link){
    //Open a window and give it focus
    var wh = window.open(link, 'logWindow');
    wh.focus();
}

//Run this function on page load
document.addEventListener("DOMContentLoaded", logLinks);

以上代码将浏览该页面,并将设置为a类的所有log标记替换为打开该链接的相关href窗口的版本然后在结果窗口上focus