window.open

2021-07-04 22:12

阅读:476

标签:提示   end   sans   als   就会   targe   san   pre   打开   

主要原理:让浏览器以为是用户主动点击的,因此可以利用onclick或者利用标签的_blank属性打开页面,

 

function OpenWindow(n, t, i, r) {
    var u = (screen.width - t) / 2 - r,
    f = (screen.height - i) / 2 - r,
    e = window.open(n, "_blank", "width=" + t + ",height=" + i + ",toolbars=0,resizable=1,left=" + u + ",top=" + f);
    e.focus()
}

window.open是javascript函数,该函数的作用是打开一个新窗口或这改变原来的窗口,不过一般用来的是打开新窗口,因为修改原来的网页地址,可以有另一个函数,那就是window.location,他可以重定向网页地址,使网页跳转到另一个页面。如果是文件,会下载,jqueryui就是这样弄的

 

一般情况下,如果你直接在js中调用window.open()函数去打开一个新窗口,浏览器会拦截你,认为你将弹出广告等用户不想得到的窗体,所以如果不想让浏览器拦截你,你可以将这个函数改为用户点击时触发,这样浏览器就认为是用户想访问这个页面,而不是你直接弹出给用户。

现在直接使用js触发按钮的click有时候不能弹出新页面,因此需要用户点击控件操作或者构造或隐藏标签弹出。
方法1:

所以常用的方法就是在按钮或者超链接里加入onclick事件,如click me这样用户点击这个超链接,浏览器会认为它是打开一个新的链接,所以就不会拦截。

 

a href="javascript:void(0)" onclick="window.open(‘http://www.baidu.com‘,‘_blank‘,‘width=300,height=400,toolbars=0,resiable=1,left=300,top=300‘);return false;">click mea>

 

方法2(优化方法1):

先用window.open打开一个窗口,然后修改地址。如var tempwindow=window.open(‘_blank‘);打开一个窗口,然后用tempwindow.location=‘http://www.baidu.com‘;使这个窗口跳转到百度,这样就会呈现弹出百度窗口的效果了。

 

 

或者,可以异步处理

 

        xx.addEventListener(‘click‘, function () {
            // 打开页面,此处最好使用提示页面
            var newWin = window.open(‘loading page‘);
            ajax().done(function() {
                // 重定向到目标页面
                newWin.location.href = ‘target url‘;
            });
        });

方法3:

 

使用其他控件调用标签的_blank属性弹出:不能在ajax内弹出,建议使用方法2。

 

 

           function newWin(url, id) {
              var a = document.createElement(‘a‘);
              a.setAttribute(‘href‘, url);
              a.setAttribute(‘target‘, ‘_blank‘);
              a.setAttribute(‘id‘, id);
              // 防止反复添加
              if(!document.getElementById(id)) {                     
                  document.body.appendChild(a);
              }
              a.click();
           }

window.open

标签:提示   end   sans   als   就会   targe   san   pre   打开   

原文地址:https://www.cnblogs.com/fpcbk/p/9841067.html


评论


亲,登录后才可以留言!