javascript - 以特定窗口大小打开链接
问题描述
我有一个可以正常工作的随机图像脚本。我正在尝试以特定窗口大小打开一个不想工作的链接并应用于随机图像链接。
如果它不在随机图像脚本中,它工作正常。
有没有办法让它在随机图像脚本中工作?
这是我的代码:
<SCRIPT LANGUAGE="Javascript">
function banner() { } ; b = new banner() ; n = 0
b[n++]= "<a href='https://youtu.be/IeIqaNR5Zs4' target='_blank'
onclick='window.open(href, '', 'height=300, width=450,
left=300, top=300'); return false;'> <IMG name=randimg
SRC='images/random/balboapark.png' alt='Balboa Park Picture'>"
b[n++]= "<a href='https://www.youtube.com/watch?v=w6UzpzMwwT8'> <IMG
name=randimg SRC='images/random/zoo.png' alt='San Diego Zoo Picture'>"
b[n++]= "<a href='https://www.youtube.com/watch?v=w6UzpzMwwT8'> <IMG
name=randimg SRC='images/random/zoo.png' alt='San Diego Beach Picture'>"
i=Math.floor(Math.random() * n) ;
document.write( b[i] )
</SCRIPT>
This opens in the specific window size.
<a target="_blank" href="https://youtu.be/IeIqaNR5Zs4"
onclick="window.open (href, '', 'height=300, width=450,
left=300, top=300'); return false;"><IMG SRC='images/random/balboapark.png'
alt='Balboa Park Picture'></a>
解决方案
如果我正确理解了您的问题,那么此代码应该可以满足您的要求。这种方法不是使用document.write()
,而是直接与 DOM API 交互,并且还使用事件侦听器click
来触发window.open()
.
请注意,此代码在堆栈溢出片段“沙盒”中不起作用,因此您需要直接在自己的项目中尝试此解决方案:
// Function configures DOM elements for a single banner based
// on provided input parameters
function createBanner(url, src, alt) {
// Create the image and assign alt/src attributes
let img = document.createElement('img');
img.setAttribute('src', src);
img.setAttribute('alt', alt);
// Create the anchor, assign attributes and click listener
let a = document.createElement('a');
a.setAttribute('href', url);
a.addEventListener('click', function() {
window.open(url, '', 'height=300, width=450, left=300, top=300');
return false
});
// Add image to anchor
a.appendChild(img);
// Return anchor for external use
return a
}
// Create banners from your input data
[
createBanner('https://youtu.be/IeIqaNR5Zs4', 'images/random/balboapark.png', 'Balboa Park Picture'),
createBanner('https://youtu.be/w6UzpzMwwT8', 'images/random/zoo.png', 'San Diego Zoo Picture'),
createBanner('https://youtu.be/w6UzpzMwwT8', 'images/random/beach.png', 'San Diego Beach Picture'),
]
.forEach(function(e, i, array) {
// Iterate through each banner, and for each banner,
// select a random banner from the collection to be
// added to the DOM
const banner = array[Math.floor(Math.random() * array.length)];
document.body.appendChild(banner);
})
推荐阅读
- node.js - 如何在 Windows 上将 NodeJS (NestJS) bachand Httpserver 作为后台进程运行?
- php - 在VueJS中的锚标记href内设置基本url
- powershell - PowerShell :: Internet Explorer 下载对话框 Num Lock On
- java - Java:如何存储和传输巨大的 Integer-ArrayList
- go - 如何确保上下文侦听器例程在主退出之前完成?
- rdp - 阻止 RDP “重试”
- c# - 如何在 Blazor WebAssembly 中删除 Origin 标头
- newrelic - Newrelic 显示没有任何数据库用户的 SQL Server 指标
- python - Appium 在连接的真实设备(android)上启动脚本,而不是在已经打开的模拟器上
- c# - “文件正在被另一个进程使用”:如何释放 ObservableCollection 绑定正在使用的文件