首页 > 解决方案 > 用 JS 显示一个随机的 css Sprite

问题描述

我有一个当前脚本,它显示来自 200-300 个文件名数组的随机图标。这行得通。

我对独立的文件/应用程序产生了新的兴趣。

我可以从 css 精灵表中选择一个随机精灵并使用 js 或 jQuery 在按下按钮时显示它吗?

我不是在这里寻找完整的代码......只是对这将带来什么的一般概念。

标签: javascriptjquery

解决方案


这就是我将如何处理它。如果您有一个带有不同精灵的精灵表。您使用 JS 向其附加不同的类,它们都代表精灵表中的不同位置

 <style>
   img_1{
    width:120px;
    height:123px;
    background-image:url('Images/newcampaign_sprite2.png');
    background-position:0px 0px;
   }
   img_2{
    width:120px;
    height:123px;
    background-image:url('Images/newcampaign_sprite2.png');
    background-position:10px 10px;
    }
   </style>


<body>
    <img id='foo1'>


    <script>
   //Initiate the variables 
   let random = Math.floor(Math.random() * 3) + 1  ;
   let classwithSpritePos ='';

   //check what random is between 1-3 and apply the sprite position class
   if(random == 1){classwithSpritePos = 'img_1'; }
   if(random == 2){classwithSpritePos = 'img_2'; }

       let img = document.getElementById('foo1');
       img.classList.add(classwithSpritePos);

</script>

推荐阅读