如何创建根据屏幕大小选择数组的函数

时间:2018-09-27 00:49:04

标签: javascript

我正在建立一个网站,它将在页面加载时加载随机图像。但是,根据屏幕大小,它将从两个阵列之一加载。我已经设置了执行此操作的功能,但是我不断收到文件未找到错误。我该如何清理?

HTML:

<article id="maryKayQuote" class="d-flex flex-row my-5 clearfix">
     <div class="dailyQuoteText">
          <!-- This is where the random daily quote will appear -->
     </div>
     <div class="quoteBackgroundImage">
          <!-- This is where the random background image will appear. -->
     </div>
     <p class="dailyQuoteTextName">&#45;Mary Kay Ash</p>
</article>

JS:

var quoteBackground = document.querySelector('.quoteBackgroundImage');

var mkImagesLarge = [
     "images/Untitled.png",
     "images/Untitled2.png",
     "images/maryKay3.jpg",
     "images/maryKay4.png"
];

var mkImagesSmall = [
     "images/quote.jpg",
     "images/quote2.jpg",
     "images/quote3.jpg",
     "images/quote4.jpg"
];

function getRandomImage() {
     var img = '<img alt=\"An image of Mary Kay Ash.\" class=\"img-fluid\" 
         src=\"';
     var randomImg;
     var w = window.outerWidth;
     if (w => 1000) {
          randomImg += Math.floor(Math.random() * mkImagesLarge.length);
          img += mkImagesLarge[randomImg];
     } else if (w <= 500) {
          randomImg += Math.floor(Math.random() * mkImagesSmall.length);
          img += mkImagesSmall[randomImg];
     }
     img += '\">';
     return img;
};

1 个答案:

答案 0 :(得分:0)

因此,您提供的代码实际上只有一个大错误。您是通过创建一个字符串并以此来构建图像元素的,但是在添加src属性时却留有很大的错误空间。

应避免将元素创建为字符串,而应通过const方法创建它们。有关更多信息,请参见:MDN Document.createElement()

我相信以下代码段可以满足您的需求,您会注意到,如果刷新,则会在代码段预览窗口中看到来自正确阵列的图像之一。

如果您的浏览器抱怨letvar,可以将它们全部切换为const quoteBackground = document.querySelector('.quoteBackgroundImage'); // As I don't have access to your images, I will be using placeholder ones: const mkImagesLarge = [ 'https://placehold.it/100x100', 'https://placehold.it/125x125', 'https://placehold.it/150x150', 'https://placehold.it/175x175', ]; // Again, same as with the large images but smaller ones this time. const mkImagesSmall = [ 'https://placehold.it/10x10', 'https://placehold.it/25x25', 'https://placehold.it/50x50', 'https://placehold.it/75x75', ]; /** * Get a random image from one of two arrays depending on the width * of the user's screen size. * * This does not create the image itself, just gets the src. * * @returns {string} The src attribte for the image when created. */ function getRandomImage() { let randomImg; let w = window.outerWidth; if (w >= 1000) { randomImg = Math.floor(Math.random() * mkImagesLarge.length); return mkImagesLarge[randomImg]; } else if (w <= 500) { randomImg = Math.floor(Math.random() * mkImagesSmall.length); return mkImagesSmall[randomImg]; } } /** * Handle the creation of the image here seperately because the image * has to be loaded asynchronously so we have to add it to the * document instead of returning it. * * @param {string} src The source of the image to create. This is from the `getRandomImage` function. */ function setRandomImage(src) { // Creating an image tag is preferred over using a string. const img = document.createElement('img'); img.alt = 'An image of Mary Key Ash'; img.classList.add('img-fluid'); img.onload = function() { quoteBackground.appendChild(img); }; img.src = src; } const backgroundImage = getRandomImage(); setRandomImage(backgroundImage);

<article id="maryKayQuote" class="d-flex flex-row my-5 clearfix">
    <div class="dailyQuoteText">
        <!-- This is where the random daily quote will appear -->
    </div>
    <div class="quoteBackgroundImage">
        <!-- This is where the random background image will appear. -->
    </div>
    <p class="dailyQuoteTextName">&#45;Mary Kay Ash</p>
</article>
getRandomImage()

更新

在您的评论中,您提到它只是显示'HTMLImageElement'而不是预期的图像,因为加载图像是异步的,并且代码段的行为与实时网站不同。

为解决此问题,我们无需将图像退回并在以后使用它(将需要创建一个Promise或使用async / await,并且如果您需要我可以编辑摘录),我们只会在加载文件时将其添加到该文件中。

我现在将一个函数拆分为两个,以便更容易判断发生了什么。 setRandomImage()现在仅返回需要创建的图像的来源,{{1}}将使用该来源并从其中创建图像元素,并在每次加载图像时将其添加到页面中。