首页 > 解决方案 > JS:在叠加层中打开随机视频、图像或链接

问题描述

我正在尝试使用 js 和 css 在叠​​加层中打开随机视频、图像或链接,但我无法使叠加层部分正确。

<a id="overlay" href="javascript:openSite()">Click to go to a random site</a>
<script>
var links = [
              "google.com",
              "youtube.com",
              "stackoverflow.com",
              "apple.com"]

           var openSite = function() {
              // get a random number between 0 and the number of links
              var randIdx = Math.random() * links.length;
              // round it, so it can be used as array index
              randIdx = parseInt(randIdx, 10);
              // construct the link to be opened
              var link = 'http://' + links[randIdx];

     var win = window.open(link, '_blank');
     win.focus();

    };
</script>

和CSS:

.overlay {
  position: fixed; /* Sit on top of the page content */
  display: none; /* Hidden by default */
  width: 100%; /* Full width (cover the whole page) */
  height: 100%; /* Full height (cover the whole page) */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5); /* Black background with opacity */
  z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
  cursor: pointer; /* Add a pointer on hover */
}

这是一个jsfiddle

标签: javascriptrandomhyperlinkoverlay

解决方案


猜猜你正在寻找这样的东西:

请注意,由于跨源安全策略,这在此代码段中不起作用!

var links = [
  "google.com",
  "youtube.com",
  "stackoverflow.com",
  "apple.com"
]

var openSite = function() {
  var randIdx = Math.random() * links.length;
  randIdx = parseInt(randIdx, 10);
  var link = 'https://' + links[randIdx];
  const iframe = document.createElement("iframe"); // create iframe
  iframe.classList.add("overlay"); // add overlay class
  document.body.append(iframe); // append to body
  iframe.src = link; // set iframe url to your random choosen link
};
.overlay {
  position: fixed; /* Sit on top of the page content */
  width: 100%; /* Full width (cover the whole page) */
  height: 100%; /* Full height (cover the whole page) */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5); /* Black background with opacity */
  z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
  cursor: pointer; /* Add a pointer on hover */
}
<a href="javascript:openSite()">Click to go to a random site</a>


推荐阅读