首页 > 解决方案 > 以特定窗口大小打开链接

问题描述

我有一个可以正常工作的随机图像脚本。我正在尝试以特定窗口大小打开一个不想工作的链接并应用于随机图像链接。

如果它不在随机图像脚本中,它工作正常。

有没有办法让它在随机图像脚本中工作?

这是我的代码:

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

标签: javascripthtml

解决方案


如果我正确理解了您的问题,那么此代码应该可以满足您的要求。这种方法不是使用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);
})


推荐阅读