簡體   English   中英

在新窗口中打開隨機圖像

[英]Open random image in new window

我無法在新窗口(不是標簽頁)中打開圖像。

該腳本位於<head>

<script type="text/javascript">

  function randomImg1() {
    var myImage1 = new Array();
    myImage1[0] = "1.jpg";
    myImage1[1] = "2.jpg";
    myImage1[2] = "3.jpg";
    var random = Math.floor(Math.random() * myImage1.length);
    document.getElementById("image").innerHTML = "<img src='" 
      + myImage1[random] + "' alt='image'></img>";

  }

</script>

我的按鈕位於<body>

<button onclick="randomImg1();OpenInNewTab();">click</button>    
<div id="image"></div>

使用https://www.w3schools.com/jsref/met_win_open.asp打開一個新窗口。 添加spec參數以使其以新窗口(而不是選項卡)的形式打開。 並確保傳遞圖像的完整路徑:

<script type="text/javascript">

  function randomImg1() {
    var myImage1 = new Array();
    myImage1[0] = "1.jpg";
    myImage1[1] = "2.jpg";
    myImage1[2] = "3.jpg";
    var random = Math.floor(Math.random() * myImage1.length);
    // create the full image URL
    var imageUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + myImage1[random];
    // open in a new window. ideally use the image's size for w and h
    window.open(imageUrl, '_blank', 'height=300,width=300');
  }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM