将 JavaScript 和文本实现到 URL 中

Implementing JavaScript and text into a URL

本文关键字:URL 实现 文本 JavaScript      更新时间:2023-09-26

我在要求一种从我拥有的列表中制作随机壁纸的方法之前发布了帖子,但我现在想知道是否不是有"images/bg-N.png"(N 是一个数字),我可以有类似的东西?

<script type="text/javascript">
  var images = ['1', '2', '3', '5', '6', '7', '8', '9', '10'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = 'url('"images/bg-" + images[Math.round(Math.random() * images.length)] + ".png"')';
</script>

这是行不通的,因为我对javascript本身知之甚少。如果有人能够为我解决这个问题,我将不胜感激!

我建议使用范围内的整数而不是数组...

var bg_min = 1;
var bg_max = 10;
var bg_url = 'images/bg-_.png';
var bg_replace = '_';
var bg_rand = Math.floor(Math.random() * (bg_max - bg_min + 1)) + bg_min;
var bg_image = bg_url.replace(bg_replace, bg_rand);
document.getElementsByClassName('mainview')[0].style.backgroundImage = "url('"+bg_image+"')";
// remove the following line in your actual page
document.getElementsByClassName('mainview')[0].innerHTML = bg_image;
<div class="mainview"></div>

对于非数字图像,我会从完整路径数组中选择一个随机元素(因此您可以使用除.png和不同位置以外的不同扩展名)......

var bg_images = [
  'images/bg-1.png',
  'images/bg-2.png',
  'images/bg-3.png',
  'images/bg-4.png',
  'images/bg-5.png',
  'http://fakeimg.pl/1/ff0000/',
  'http://fakeimg.pl/2/ffff00/',
  'http://fakeimg.pl/3/00ff00/',
  'http://fakeimg.pl/4/00ffff/',
  'http://fakeimg.pl/5/0000ff/'
];
var random_bg_image = bg_images[Math.floor(Math.random()*bg_images.length)];
document.getElementsByClassName('mainview')[0].style.backgroundImage = "url("+random_bg_image+")";
<div class="mainview" style="width:300px;height:100px;"></div>

您不需要额外的引号。

<script type="text/javascript">
  var images = ['1', '2', '3', '5', '6', '7', '8', '9', '10'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = 'url(images/bg-' + images[Math.round(Math.random() * images.length)] + '.png)';
</script>

据我所知,这是一个简单的语法问题:

<script type="text/javascript">
  var images = ['1', '2', '3', '5', '6', '7', '8', '9', '10'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = "url('images/bg-" + images[Math.round(Math.random() * images.length)] + ".png')";
</script>