目标:快速而肮脏的应用程序(仅限客户端)从一页获取一些参数并将结果放到新页面上,该页面可以打印然后关闭。然后可以更改原始页面上的参数并弹出新页面。
以此为起点: https://developer.mozilla.org/en/DOM/window.open http://www.yourhtmlsource.com/javascript/popupwindows.html
概念证明(最终版本将有大约 10 个输入/参数)
HTML 片段
<input type="text" id="x">
<form>
<input type=button value="Calculate" onClick="javascript:genResults()">
</form>
JS
function dirtypop(arg)
{
var popwin=window.open('','name','height=300,width=400,status=1,center=1');
popwin.document.write('<html><head><title>Square</title>');
popwin.document.write('</head><body>');
popwin.document.write('<h1>Squared plus one is: '+arg+'</h1>');
popwin.document.write('<p><a href="javascript:self.close()">Close</a> this window</p>');
popwin.document.write('</body></html>');
popwin.document.close();
};
function genResults()
{
x = document.getElementById('x').value;
if (x == parseFloat(x))
{
dirtypop(x*x+1);
}
};
这有效(在 FF3.5 和 Chrome 上测试),但新窗口不会弹出到中心。怎么居中呢? Mozzila 说需要 chrome=yes 并谈论 UniversalPrivilege 脚本,那些是什么样的野兽?
还有什么可以改进的吗?
最佳答案
这是我的自定义跨浏览器脚本之一,可以动态重用该脚本以将任何大小的任何弹出窗口在屏幕上居中:
// here's the script function popWindow(url,winName,w,h) { if (window.open) { if (poppedWindow) { poppedWindow = ''; } //GET SIZE OF WINDOW/SCREEN windowW = w; windowH = h; var windowX = (screen.width/2)-(windowW/2); var windowY = (screen.height/2)-(windowH/2); var myExtra = "status=no,menubar=no,resizable=yes,toolbar=no,scrollbars=yes,addressbar=no"; var poppedWindow = window.open(url,winName,'width='+w+',height='+h+',top='+windowY+',left=' + windowX + ',' + myExtra + ''); setTimeout(refreshThis,3000); } else { alert('Your security settings are not allowing our popup windows to function. Please make sure your security software allows popup windows to be opened by this web application.'); } }
// and you would call it like this: popWindow('http://www.myurl.com/','myPoppedWindowName','500','400'); // With this example call you would pop a window with a url of http://www.myurl.com/ // which is given the name of myPoppedWindowName // and a width of 500px along with height of 400px // which gets centered on the screen according to these size parameters
考虑到它确实是一个跨浏览器实现,包括对 2001 年浏览器的反向兼容性,这将起到作用。它还包含一项检查,以确保最终用户启用了弹出窗口。
关于javascript - 使用 Javascript 将弹出窗口居中并传递 html 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1977775/